第1章 redis存儲系統
1.1 redis概述
- REmote DIctionary Server(Redis)是一個基於key-value鍵值對的持久化數據庫存儲系統。redis和大名鼎鼎的Memcached緩存服務軟件很像,可是redis支持的數據存儲類型比memcached更豐富,包括strings(字符串),lists(列表),sets(集合)和sorted sets(有序集合)等。
- 這些數據類型支持push/pop,add/remove及取交集,並集和差集及更豐富的操做,並且這些操做都是原子性的。在此基礎上,redis支持各類不一樣方式的排序。與memcached緩存服務同樣,爲了保證效率,數據都是緩存在內存中提供服務。和memcached不一樣的是,redis持久化緩存服務還會週期性的把更新的數據寫入到磁盤以及把修改的操做記錄追加到文件裏記錄下來,比memcached更有優點的是,redis還支持master-slave(主從)同步,這點很相似關係型數據庫MySQL主從複製功能。
- Redis是一個開源的使用C語言編寫(3萬多行代碼),支持網絡,可基於內存亦可持久化的日誌型,Key-Value數據庫,並提供多種語言的API。從2010年3月15日起,Redis的開發工做由VMware主持。
- Redis軟件的出現,再必定程度上彌補了memcached這類key-value內存緩存服務的不足,在部分場合能夠對關係數據庫起到很好的補充做用。redis提供了Python,Ruby,Erlang,PHP客戶端,使用起來很方便。redis官方文檔以下:
- http://www.redis.io/documentation
- http://www.redis.cn/
- http://www.redis.io/topics/introduction
1.2 redis特色
- key-value鍵值類型存儲
- 支持數據可靠存儲及落地
- 單進程單線程高性能服務器
- crash safe & recovery slow
- 單機qps能夠達到10W
- 適合小數據量高速讀寫訪問
1.3 Redis優勢
- 與memcached不一樣,Redis能夠持久化存儲數據
- 性能很高:Redis能支持超過10W每秒的讀寫頻率。
- 豐富的數據類型:Redis支持二進制的Strings,Lists,Hashes,Sets及sorted Sets等數據類型操做
- 原子:Redis的全部操做都是原子性的,同時Redis還支持對幾個操做全並後的原子性執行
- 豐富的特性:Redis還支持publish/subscribe(發佈/訂閱),通知,key過時等等特性。
- redis支持異機主從複製。
1.4 redis缺陷與陷阱
- 系統運行有毛刺
- 不一樣命令延遲差異極大
- 內存管理開銷大(設置低於物理內存3/5)
- buffer io形成系統OOM(內存溢出)
1.5 redis的數據類型
做爲Key-value型存儲系統數據庫,Redis提供了鍵(Key)和值(value)映射關係。可是,除了常規的數值或字符串,Redis的鍵值還能夠是如下形式之一,下面爲最爲經常使用的數據類型:php
- String 字符串
- Hash 哈希表
- List 列表
- Set 集合
- Sorted set 有序集合
1.6 redis 持久化
一般,Redis將數據存儲於內存中,或被配置爲使用虛擬內存。經過兩種方式能夠實現數據持久化:使用快照(snapshot)的方式,將內存中的數據不斷寫入磁盤,或使用相似MySQL的binlog日誌(aof但並不用於主從同步)方式,記錄每次更新的日誌。前者性能較高,可是可能會引發必定程度的數據丟失;後者相反。css
#名詞解釋
#Snapshot(快照)
save 900 1 #900秒有1key容量被更新,則觸發快照寫入磁盤
save 300 10
save 60 10000
#AOF(更新日誌)
appendfsync always #老是記錄更新內容
appendfsync everysec #每秒記錄更新內容
appendfsync no #不記錄更新內容
特別提示:
若是選擇了快照的策略,那麼快照在每次進行保存的時候,都會阻礙執行前端的客戶端請求。
快照會一次性將內存裏的數據全都寫進磁盤。html
1.7 redis的應用場景
(1)MySQL+Memcached網站架構問題前端
經過MySQL數據庫存儲數據庫數據,加上經過Memcached把熱點數據存放到內存cache裏,達到加速數據訪問減輕數據庫壓力的目的,這是絕大部分公司都曾經使用過這樣的架構,但隨着業務數據量的不斷增長,和訪問量的持續增加,不少問題就會暴露出來:python
- 須要不斷的對MySQL進行拆庫拆表,Memcached也需不斷跟着擴容,擴容和維護工做佔據大量開發運維時間。
- Memcached與MySQL數據庫數據一致性問題是個老大難。
- Memcached數據命中率低或down機,會致使大量訪問直接穿透到數據庫,致使MySQL沒法支撐訪問。
- 跨機房cache同步及cache數據一致性問題
(2)redis的最佳應用場景mysql
- Redis最佳試用場景是所有數據in-memory
- Redis更多場景是做爲Memcached的替代品來使用。
- 數據比較重要,對數據一致性有必定要求的業務。
- 當須要除key/value以外的更多數據類型支持時,使用Redis更合適。
- 須要提供主從同步以及負載均衡分佈式應用場景(redis主從同步)
更多linux
a.Redis做者談Redis應用場景
http://blog.nosqlfan.com/html/2235.htmlnginx
b.使用Redis bitmap進行活躍用戶統計
http://blog.nosqlfan.com/html/3501.htmlgit
- 計數,cache服務,展現最近,最熱,點擊率最高,活躍度最高等等條件的top list,用戶最近訪問記錄,Relation List/Message Queue,粉絲列表。
- Key-Value Store 更加註重對海量數據存取的性能,分佈式,擴展性支持上,並不須要傳統關係數據庫的一些特徵,例如:Schema,事務,完整SQL查詢支持等等,所以在分佈式環境下的性能相對於傳統的關係數據庫有較大提高。
1.8 redis的應用案例
sina使用redis案例:github
(1)application -->redis
(2)應用程序首先訪問Redis,只有當Redis沒有數據或訪問失敗時訪問redis。
(3)二次開發實現MySQL和redis互相同步
MySQL -->Redis複製
- 經過RBR解析BINLOG同步到redis
- Redis提供特定數據結構的讀訪問
- 實現關係型數據轉變成隊列數據
Redis -->MySQL複製
- Redis提供特定數據結構的讀寫
- 經過replication接口同時寫入到MySQL
新浪爲何用redis?
- 數據結構(Data Structure)需求愈來愈多,但Memcache中沒有,影響開發效率。
- 性能需求,隨着讀操做的量的上升須要解決,經歷的過程有:數據庫讀寫分離(M/S)-->數據庫使用多個Slave -->增長Cache(memcache)-->轉到Redis
- 解決寫的問題:水平拆分,對錶的拆分,將有的用戶放在這個表,有的用戶放在另一個表。
- 可靠性需求:Cache的「雪崩」問題讓人糾結;Cache面臨着快速恢復的挑戰。
- 開發成本需求:Cache和DB的一致性維護成本愈來愈高(先清理DB,再清理緩存,不行啊,太慢了!)開發須要跟上不斷涌入的產品需求,硬件成本最貴的就是數據庫層面的機器,基本上比前端的機器要貴幾倍,主要是IO密集型,很耗硬件。
- 維護性複雜:一致性維護成本愈來愈高。BerkeleyDB使用B樹,會一直寫新的,內部不會有文件從新組織;這樣會致使文件愈來愈大;大的時候須要進行文檔歸檔,歸檔的操做要按期作;這樣,就須要有必定的down time。
因此基於以上考慮,新浪選擇了Redis
1.9 Redis的生產經驗教訓
- 必定要進行Master-slave主從同步配置,在出現服務故障時能夠切換
- 在master禁用數據持久化,只須要在slave上配置數據持久化
- 物理內存+虛擬內存不足,這個時候dump一直死着,時間久了機器掛掉。這個狀況就是災難!
- 當Redis物理內存使用超過內存總容量的3/5時就會開始比較危險了,就開始作swap,內存碎片大!
- 當達到最大內存時,會清空帶有過時時間的key,即便key未到過時時間。
- redis與DB同步寫的問題,先寫DB,後寫redis,由於寫內存基本上沒有問題。
第2章 快速部署一個redis環境
2.1 Redis部署環境搭建
主機名 | eth0 | 用途 |
---|---|---|
Master-redis01 | 10.0.0.135 | 主Redis |
Slave-redis02 | 10.0.0.136 | 從Redis |
2.2 開始安裝redis服務
在redis的官方網站(http://www.redis.io)下載最新的穩定版本redis。
wget -q http://download.redis.io/releases/redis-2.8.9.tar.gz
#在redis01和redis02都執行以下操做
[root@redis01 ~]# tar xf redis-2.8.9.tar -C /usr/src/
[root@redis01 ~]# cd /usr/src/redis-2.8.9/
[root@redis01 redis-2.8.9]# make MALLOC=jemalloc
[root@redis01 redis-2.8.9]# make PREFIX=/usr/local/redis install
[root@redis01 redis-2.8.9]# LANG=en
[root@redis01 redis-2.8.9]# tree /usr/local/redis/bin/
/usr/local/redis/bin/
├── redis-benchmark
├── redis-check-aof
├── redis-check-dump
├── redis-cli
└── redis-server
0 directories, 5 files
命令執行完成以後,會在/usr/local/redis/bin/目錄下生成5個可執行文件,分別是:
redis-server,redis-cli,redis-benchmark,redis-check-aof,redis-check-dump
它們的做用以下:
redis-server #Redis服務器的daemon啓動程序
redis-cli #Redis命令操做工具。固然,你也能夠用telnet根據其純文本協議來操做
redis-benchmark #Redis性能測試工具,測試Redis在你的系統及你的配置下的讀寫性能。
redis-check-aof #對更新日誌appendonly.aof檢查,是否可用,相似檢查mysql binlog的工具
redis-check-dump #用於本地數據庫rdb文件的檢查
2.3 配置並啓動redis服務
(1)配置啓動命令
操做過程:
[root@redis01 redis-2.8.9]# ln -s /usr/local/redis/bin/* /usr/local/bin/
(2)查看命令幫助:
[root@redis01 redis-2.8.9]# redis-server -h
Usage: ./redis-server [/path/to/redis.conf] [options]
./redis-server - (read config from stdin)
./redis-server -v or --version
./redis-server -h or --help
./redis-server --test-memory <megabytes>
Examples:
./redis-server (run the server with default conf)
./redis-server /etc/redis/6379.conf
./redis-server --port 7777
./redis-server --port 7777 --slaveof 127.0.0.1 8888
./redis-server /etc/myredis.conf --loglevel verbose
Sentinel mode:
./redis-server /etc/sentinel.conf --sentinel
(3)啓動redis服務
操做過程:
#從源程序目錄複製redis.conf到程序安裝目錄下
[root@redis01 redis-2.8.9]# cd /usr/src/redis-2.8.9/
[root@redis01 redis-2.8.9]# pwd
/usr/src/redis-2.8.9
[root@redis01 redis-2.8.9]# mkdir /usr/local/redis/conf
[root@redis01 redis-2.8.9]# cp redis.conf /usr/local/redis/conf/
#啓動redis服務
[root@redis01 redis-2.8.9]# redis-server /usr/local/redis/conf/redis.conf &
#查看redis進程啓動狀況
[root@redis01 redis-2.8.9]# ps -ef | grep redis | grep -v grep
root 3169 1288 0 10:17 pts/0 00:00:00 redis-server *:6379
特別提示:
redis啓動成功後,在最後會出現以下警示信息:
[3169] 02 Oct 10:17:30.689 # Server started, Redis version 2.8.9
[3169] 02 Oct 10:17:30.690 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
[3169] 02 Oct 10:17:30.690 * The server is now ready to accept connections on port 6379
#警示大概意思爲:
overcommit_memory被設置爲了0.若是內存不夠的狀況下後臺保存可能會失敗;要解決這個問題,須要在/etc/sysctl.conf配置文件中將vm.overcommit_memory設置爲1;或者經過命令「sysctl vm.overcommit_memory=1」來修改。
所以,咱們作一下處理後在啓動redis進程
[root@redis01 redis-2.8.9]# pkill redis
[root@redis01 redis-2.8.9]# sysctl vm.overcommit_memory=1
vm.overcommit_memory = 1
[root@redis01 redis-2.8.9]# redis-server /usr/local/redis/conf/redis.conf &
通過處理後,再啓動redis就沒有任何警告了。
vm.overcommit_memory參數說明:
根據內核文檔,該參數有三個值,分別是:
0:當用戶空間請求更多的內存時,內核嘗試估算出剩餘可用的內存。
1:當設這個參數值爲1時,內核容許超量使用內存直到用完爲止,主要用於科學計算
2:當設這個參數值爲2時,內核會使用一個毫不過量使用內存的算法,即系統整個內存地址空間不能超過swap+50%的RAM值,50%參數的設定是在overcommit_ratio中設定。
測試關閉redis服務的命令
redis-cli shutdown
關閉redis進程
[root@redis01 redis-2.8.9]# ps -ef | grep redis | grep -v grep
root 3200 1288 0 10:38 pts/0 00:00:08 redis-server *:6379
[root@redis01 redis-2.8.9]# redis-cli shutdown
[3200] 02 Oct 12:43:46.621 # User requested shutdown...
[3200] 02 Oct 12:43:46.621 * Saving the final RDB snapshot before exiting.
[3200] 02 Oct 12:43:46.630 * DB saved on disk
[3200] 02 Oct 12:43:46.631 # Redis is now ready to exit, bye bye...
[1]+ Done redis-server /usr/local/redis/conf/redis.conf
[root@redis01 redis-2.8.9]# ps -ef | grep redis | grep -v grep
[root@redis01 redis-2.8.9]# redis-server /usr/local/redis/conf/redis.conf
2.4 經過客戶端操做redis數據庫
下面咱們來簡單操做一下數據庫。
插入數據:設置一個key-value對
[root@redis01 redis-2.8.9]# redis-cli #經過客戶端鏈接本地redis
127.0.0.1:6379> set id 001 #寫入一條數據key(id),value(001)
OK
127.0.0.1:6379> get id #取值key(id)
"001" #顯示key對應的值
127.0.0.1:6379> del id #刪除key(id)
(integer) 1 #1表示成功
127.0.0.1:6379> exists id #驗證key是否存在
(integer) 0 #0表示不存在
127.0.0.1:6379> get id #取key的值
(nil) #報錯信息
127.0.0.1:6379> set user001 benet
OK
127.0.0.1:6379> set user002 yunjisuan
OK
127.0.0.1:6379> set user003 yun123
OK
127.0.0.1:6379> get user001
"benet"
127.0.0.1:6379> get user002
"yunjisuan"
127.0.0.1:6379> keys * #查看redis裏全部的key
1) "user003"
2) "user002"
3) "user001"
2.5 更多操做方式及命令幫助
(1)redis數據庫的表模式
127.0.0.1:6379> keys * #查看全部key
1) "user003"
2) "user002"
3) "user001"
127.0.0.1:6379> select 1 #切換到表1模式
OK
127.0.0.1:6379[1]> keys * #查詢全部key
(empty list or set) #什麼都沒有
127.0.0.1:6379[1]> set name wangwu #寫入一個key-value對
OK
127.0.0.1:6379[1]> keys * #查看全部key
1) "name" #key(name)已經有了
127.0.0.1:6379[1]> get name #查看key(name)的值
"wangwu"
127.0.0.1:6379[1]> select 0 #切換回表0模式(初始模式)
OK
127.0.0.1:6379> keys * #查看全部key
1) "user003"
2) "user002"
3) "user001"
(2)redis-cli客戶端的遠程鏈接及非交互式操做數據庫
[root@redis01 redis-2.8.9]# redis-cli -h 10.0.0.135 -p 6379
10.0.0.135:6379> quit
[root@redis01 redis-2.8.9]# redis-cli -h 10.0.0.135 -p 6379 set aaa 111
OK
[root@redis01 redis-2.8.9]# redis-cli -h 10.0.0.135 -p 6379 get aaa
"111"
(3)經過telnet鏈接redis數據庫
telnet 10.0.0.135 6379
2.6 redis命令幫助
(1)redis-cli客戶端命令幫助:
10.0.0.135:6379> ? #查看幫助命令用法
redis-cli 2.8.9
Type: "help @<group>" to get a list of commands in <group>
"help <command>" for help on <command>
"help <tab>" to get a list of possible help topics
"quit" to exit
10.0.0.135:6379> help #查看幫助命令用法
redis-cli 2.8.9
Type: "help @<group>" to get a list of commands in <group>
"help <command>" for help on <command>
"help <tab>" to get a list of possible help topics
"quit" to exit
10.0.0.135:6379> help set #查看set命令用法
SET key value [EX seconds] [PX milliseconds] [NX|XX]
summary: Set the string value of a key
since: 1.0.0
group: string
10.0.0.135:6379>
(2)經過help命令來查找命令
#輸入help + 空格 + 屢次<Tab>鍵來切換全部命令
10.0.0.135:6379> help @generic #這裏須要狂按Tab鍵
2.7 redis安全
(1)爲redis客戶端設置外部連接密碼
警告:
由於redis速度至關快,因此在一臺比較好的服務器下,一個外部的用戶能夠在1秒內進行上萬次的密碼嘗試,這意味着你須要指定很是很是強大的密碼來防止暴力破解。
[root@redis01 redis-2.8.9]# grep -n requirepass /usr/local/redis/conf/redis.conf #修改redis配置文件,添加密碼
198:# If the master is password protected (using the "requirepass" configuration
339:# requirepass foobared
[root@redis01 redis-2.8.9]# sed -i '339 s@# requirepass foobared@requirepass yunjisuan@g' #密碼是yunjisuan /usr/local/redis/conf/redis.conf
[root@redis01 redis-2.8.9]# grep -n requirepass /usr/local/redis/conf/redis.conf
198:# If the master is password protected (using the "requirepass" configuration
339:requirepass yunjisuan
重啓redis後測試
#重啓redis進程
[root@redis01 redis-2.8.9]# ps -ef | grep redis | grep -v grep
root 3442 1288 0 13:40 pts/0 00:00:17 redis-server *:6379
[root@redis01 redis-2.8.9]# redis-cli shutdown
[3442] 02 Oct 18:17:03.370 # User requested shutdown...
[3442] 02 Oct 18:17:03.370 * Saving the final RDB snapshot before exiting.
[3442] 02 Oct 18:17:03.380 * DB saved on disk
[3442] 02 Oct 18:17:03.380 # Redis is now ready to exit, bye bye...
[1]+ Done redis-server /usr/local/redis/conf/redis.conf
[root@redis01 redis-2.8.9]# ps -ef | grep redis | grep -v grep
[root@redis01 redis-2.8.9]# redis-server /usr/local/redis/conf/redis.conf &
[root@redis01 redis-2.8.9]# ps -ef | grep redis | grep -v grep
root 3843 1288 0 18:18 pts/0 00:00:00 redis-server *:6379
#測試驗證效果
#第一種登錄驗證方式
[root@redis01 redis-2.8.9]# redis-cli #登錄本地redis
127.0.0.1:6379> set name 3333 #存數據
(error) NOAUTH Authentication required. #沒有驗證權限
127.0.0.1:6379> keys * #查看全部key
(error) NOAUTH Authentication required. #沒有驗證權限
127.0.0.1:6379> auth yunjisuan #提交驗證密碼
OK #驗證經過
127.0.0.1:6379> keys * #查看全部keys
1) "user003"
2) "ab"
3) "user002"
4) "aaa"
5) "user001"
#第二種登陸驗證方式
[root@redis01 redis-2.8.9]# redis-cli -a yunjisuan #登錄時提交密碼
127.0.0.1:6379> keys *
1) "user003"
2) "ab"
3) "user002"
4) "aaa"
5) "user001"
特別提示:
redis沒有用戶的概念,只能設置鏈接密碼,而且redis的鏈接速度很是快。所以密碼須要設置的很複雜才安全。
(2)將危險的命令更名
#查看配置文件說明
[root@redis01 redis-2.8.9]# cat -n /usr/local/redis/conf/redis.conf | sed -n '326,359p'
326 ################################## SECURITY ###################################安全相關
327
328 # Require clients to issue AUTH <PASSWORD> before processing any other
329 # commands. This might be useful in environments in which you do not trust
330 # others with access to the host running redis-server.
331 #
332 # This should stay commented out for backward compatibility and because most
333 # people do not need auth (e.g. they run their own servers).
334 #
335 # Warning: since Redis is pretty fast an outside user can try up to
336 # 150k passwords per second against a good box. This means that you should
337 # use a very strong password otherwise it will be very easy to break.
338 #
339 requirepass yunjisuan ##添加的密碼驗證
340
341 # Command renaming.
342 #
343 # It is possible to change the name of dangerous commands in a shared
344 # environment. For instance the CONFIG command may be renamed into something
345 # hard to guess so that it will still be available for internal-use tools
346 # but not available for general clients.
347 #
348 # Example:
349 #
350 # rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52
351 #
352 # It is also possible to completely kill a command by renaming it into
353 # an empty string:
354 #
355 # rename-command CONFIG "" ##命令修改示例
356 #
357 # Please note that changing the name of commands that are logged into the
358 # AOF file or transmitted to slaves may cause problems.
359
#修改配置文件
[root@redis01 redis-2.8.9]# sed -i '359i rename-command set "sset"' /usr/local/redis/conf/redis.conf
[root@redis01 redis-2.8.9]# sed -n '359p' /usr/local/redis/conf/redis.conf
rename-command set "sset"
#重啓redis進程
[root@redis01 redis-2.8.9]# redis-cli -a yunjisuan shutdown
[3843] 02 Oct 18:56:54.245 # User requested shutdown...
[3843] 02 Oct 18:56:54.245 * Saving the final RDB snapshot before exiting.
[3843] 02 Oct 18:56:54.255 * DB saved on disk
[3843] 02 Oct 18:56:54.255 # Redis is now ready to exit, bye bye...
[1]+ Done redis-server /usr/local/redis/conf/redis.conf
[root@redis01 redis-2.8.9]# redis-server /usr/local/redis/conf/redis.conf &
#驗證命令更名效果
[root@redis01 redis-2.8.9]# redis-cli -a yunjisuan
127.0.0.1:6379> set xxx 555 #命令輸入錯誤(由於修改過了)
(error) ERR unknown command 'set'
127.0.0.1:6379> sset xxx 555 #寫入key-value正確
OK
127.0.0.1:6379> get xxx
"555"
2.8 爲php安裝redis客戶端擴展
(1)獲取源碼包
wget https://github.com/nicolasff/phpredis/archive/master.zip
(2)安裝
[root@redis01 ~]# ls -l phpredis-master.tar.gz
-rw-r--r--. 1 root root 164509 Oct 2 19:23 phpredis-master.tar.gz
[root@redis01 ~]# tar xf phpredis-master.tar.gz -C /usr/src/
[root@redis01 ~]# cd /usr/src/phpredis-master/
[root@redis01 phpredis-master]# /usr/local/php/bin/phpize
[root@redis01 phpredis-master]# ./configure --with-php-config=/usr/local/php/bin/php-config
[root@redis01 phpredis-master]# make && make install
(3)修改php.ini設置,重啓php
#添加
echo "extension = redis.so" >> /usr/local/php/lib/php.ini
#將php.ini配置文件中的extension_dir修改爲以下:
extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/"
2.9 開發php程序操做redis
在操做以前,請將以前redis配置文件裏修改的redis命令註釋掉
[root@redis01 scripts]# cat redis.php
#!/bin/bash
<?php
$redis = new Redis();
$redis -> connect("10.0.0.135",6379);
$redis -> auth("yunjisuan");
$redis -> set("name","yunjisuan");
$var = $redis -> get("name");
echo "$var\n";
?>
2.10 安裝Python redis客戶端操做redis
wget https://pypi.python.org/packages/source/r/redis/redis-2.10.1.tar.gz
tar xf redis-2.10.1.tar.gz
cd redis-2.10.1
python setup.py install
開發python程序操做redis
在操做前請將以前redis配置文件裏修改的redis命令註釋掉,不然報錯
[root@redis01 redis-2.10.1]# python
Python 2.6.6 (r266:84292, Nov 22 2013, 12:16:22)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import redis #引用redis支持庫
>>> r = redis.Redis(host='10.0.0.135',port='6379',password='yunjisuan') #創建redis數據庫的鏈接對象(面向對象方式)
>>> r.set('name','benet') #操做對象調用set方法寫入數據
True
>>> r.get('name') #操做對象調用get方式讀取數據
'benet'
>>> r.dbsize() #操做對象查看redis數據庫的數據條數
1L
>>> r.keys() #查看全部的key
['name']
>>> exit() #退出
2.11 經過Web界面鏈接Python程序展現redis
開發Python腳本
[root@redis01 scripts]# cat python-redis.py
#/usr/bin/python
from wsgiref.simple_server import make_server
import redis
def get_redis():
r = redis.Redis(host='10.0.0.135',port='6379',password='yunjisuan',db=0)
r.set('name','yunyunyun')
return r.get('name')
def hello_world_app(environ,start_response):
status = '200 OK' #HTTP Status
headers = [('Content-type','text/plain')] #HTTP Headers
start_response(status,headers)
# The returned object is going to be printed
return get_redis()
httpd = make_server('',8000,hello_world_app)
print "Serving on port 8000..."
# Server until process is killed
httpd.serve_forever()
啓動python腳本
注意關閉iptables
[root@redis01 scripts]# python python-redis.py
Serving on port 8000... #監聽8000端口
經過客戶端瀏覽器鏈接Python程序
2.12 解讀redis默認配置文件
#redis支持include功能
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '30,31p'
30 # include /path/to/local.conf
31 # include /path/to/other.conf
#redis是否後臺運行
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '37p'
37 daemonize no
#pid號保存文件的位置
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '41p'
41 pidfile /var/run/redis.pid
#redis默認監聽端口
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '45p'
45 port 6379
#調整tcp監聽隊列
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '54p'
54 tcp-backlog 511
#調整redis的監聽地址
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '63,64p'
63 # bind 192.168.1.100 10.0.0.1
64 # bind 127.0.0.1
#調整客戶端超時時間
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '74p'
74 timeout 0
#調整tcp的會話保持時間
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '90p'
90 tcp-keepalive 0
#調整日誌級別
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '98p'
98 loglevel notice
#redis日誌記錄位置,默認是打印到屏幕上
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '103p'
103 logfile ""
#是否啓用syslog來接收日誌(好比日誌集中收集)
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '113p'
113 # syslog-facility local0
#設置數據庫的數量,若是缺省,默認爲0(select0...select 15)
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '118p'
118 databases 16
#redis快照設置
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '120,144p'
120 ################################ SNAPSHOTTING ################################
121 #
122 # Save the DB on disk:
123 #
124 # save <seconds> <changes>
125 #
126 # Will save the DB if both the given number of seconds and the given
127 # number of write operations against the DB occurred.
128 #
129 # In the example below the behaviour will be to save:
130 # after 900 sec (15 min) if at least 1 key changed
131 # after 300 sec (5 min) if at least 10 keys changed
132 # after 60 sec if at least 10000 keys changed
133 #
134 # Note: you can disable saving at all commenting all the "save" lines.
135 #
136 # It is also possible to remove all the previously configured save
137 # points by adding a save directive with a single empty string argument
138 # like in the following example:
139 #
140 # save "" #若是不想保存在磁盤,就如此設置
141
142 save 900 1 #900秒內至少1key數據變化,但會阻塞用戶請求,高併發時不用
143 save 300 10 #300秒內至少10key數據變化,但會阻塞用戶請求,高併發時不用
144 save 60 10000 #60秒內至少10000key數據變化,但會阻塞用戶請求,高併發時不用
#若是bgsave出錯是否中止寫入
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '159p'
159 stop-writes-on-bgsave-error yes
#redis將數據存儲在磁盤的什麼位置
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '177p'
177 dbfilename dump.rdb
#指定redis配置文件當前工做的路徑(指定dbfilename的當前路徑位置)
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '187p'
187 dir ./
#給redis設定密碼
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '339p'
339 requirepass yunjisuan
#修改redis操做命令的名稱
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '355,357p'
355 # rename-command CONFIG ""
356 # rename-command set ""
357 # rename=command get yunjisuan
#設定redis內存限制(可是內存用完後,redis就會開始刪除key)
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '398p'
398 # maxmemory <bytes>
#設定redis內存清理的算法
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '403,408p'
403 # volatile-lru -> remove the key with an expire set using an LRU algorithm
404 # allkeys-lru -> remove any key accordingly to the LRU algorithm
405 # volatile-random -> remove a random key with an expire set
406 # allkeys-random -> remove a random key, any key
407 # volatile-ttl -> remove the key with the nearest expire time (minor TTL)
408 # noeviction -> don't expire at all, just return an error on write operations
#設定redis內存限制及內存清理的算法示例
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '421p'
421 # maxmemory-policy volatile-lru
#關於redis的流模式的存儲說明
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '431,449p'
431 ############################## APPEND ONLY MODE ###############################
432
433 # By default Redis asynchronously dumps the dataset on disk. This mode is
434 # good enough in many applications, but an issue with the Redis process or
435 # a power outage may result into a few minutes of writes lost (depending on
436 # the configured save points).
437 #
438 # The Append Only File is an alternative persistence mode that provides
439 # much better durability. For instance using the default data fsync policy
440 # (see later in the config file) Redis can lose just one second of writes in a
441 # dramatic event like a server power outage, or a single write if something
442 # wrong with the Redis process itself happens, but the operating system is
443 # still running correctly.
444 #
445 # AOF and RDB persistence can be enabled at the same time without problems.
446 # If the AOF is enabled on startup Redis will load the AOF, that is the file
447 # with the better durability guarantees.
448 #
449 # Please check http://redis.io/topics/persistence for more information.
#是否啓用AOF存儲模式
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '451p'
451 appendonly no
#設定AOF文件的存儲位置
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '455p'
455 appendfilename "appendonly.aof" #並不用於主從同步,只是redis在啓動時,讀取此文件用於恢復數據
#設定AOF同步存儲的時間週期
[root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '481p'
481 appendfsync everysec #每秒或不用