第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的鍵值還可以是以下形式之一,下面為最為常用的數據類型:
- String 字符串
- Hash 哈希表
- List 列表
- Set 集合
- Sorted set 有序集合
1.6 redis 持久化
通常,Redis將數據存儲於內存中,或被配置為使用虛擬內存。通過兩種方式可以實現數據持久化:使用快照(snapshot)的方式,將內存中的數據不斷寫入磁盤,或使用類似MySQL的binlog日志(aof但並不用於主從同步)方式,記錄每次更新的日志。前者性能較高,但是可能會引起一定程度的數據丟失;后者相反。
#名詞解釋
#Snapshot(快照)
save 900 1 #900秒有1key容量被更新,則觸發快照寫入磁盤
save 300 10
save 60 10000
#AOF(更新日志)
appendfsync always #總是記錄更新內容
appendfsync everysec #每秒記錄更新內容
appendfsync no #不記錄更新內容
特別提示:
如果選擇了快照的策略,那么快照在每次進行保存的時候,都會阻礙執行前端的客戶端請求。
快照會一次性將內存里的數據全都寫進磁盤。
1.7 redis的應用場景
(1)MySQL+Memcached網站架構問題
通過MySQL數據庫存儲數據庫數據,加上通過Memcached把熱點數據存放到內存cache里,達到加速數據訪問減輕數據庫壓力的目的,這是絕大部分公司都曾經使用過這樣的架構,但隨着業務數據量的不斷增加,和訪問量的持續增長,很多問題就會暴露出來:
- 需要不斷的對MySQL進行拆庫拆表,Memcached也需不斷跟着擴容,擴容和維護工作占據大量開發運維時間。
- Memcached與MySQL數據庫數據一致性問題是個老大難。
- Memcached數據命中率低或down機,會導致大量訪問直接穿透到數據庫,導致MySQL無法支撐訪問。
- 跨機房cache同步及cache數據一致性問題
(2)redis的最佳應用場景
- Redis最佳試用場景是全部數據in-memory
- Redis更多場景是作為Memcached的替代品來使用。
- 數據比較重要,對數據一致性有一定要求的業務。
- 當需要除key/value之外的更多數據類型支持時,使用Redis更合適。
- 需要提供主從同步以及負載均衡分布式應用場景(redis主從同步)
更多
a.Redis作者談Redis應用場景
http://blog.nosqlfan.com/html/2235.html
b.使用Redis bitmap進行活躍用戶統計
http://blog.nosqlfan.com/html/3501.html
- 計數,cache服務,展示最近,最熱,點擊率最高,活躍度最高等等條件的top list,用戶最近訪問記錄,Relation List/Message Queue,粉絲列表。
- Key-Value Store 更加注重對海量數據存取的性能,分布式,擴展性支持上,並不需要傳統關系數據庫的一些特征,例如:Schema,事務,完整SQL查詢支持等等,因此在分布式環境下的性能相對於傳統的關系數據庫有較大提升。
![]()
1.8 redis的應用案例
sina使用redis案例:
(1)application -->redis
(2)應用程序首先訪問Redis,只有當Redis沒有數據或訪問失敗時訪問redis。
(3)二次開發實現MySQL和redis互相同步
MySQL -->Redis復制
- 通過RBR解析BINLOG同步到redis
- Redis提供特定數據結構的讀訪問
- 實現關系型數據轉變成隊列數據
Redis -->MySQL復制
- Redis提供特定數據結構的讀寫
- 通過replication接口同時寫入到MySQ
新浪為什么用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部署環境搭建
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 #每秒或不用