第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 有序集合
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsISPrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdsATOfd3bkFGazxCMx8VesATMfhHLlN3XnxCMwEzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsYTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cmbw5SZ5cDOiBTYjFWNycjN2gjYkRGN3UGZkljMkJTO4MTYx8CX0IzLclDMxIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjL3M3Lc9CX6MHc0RHaiojIsJye.png)
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接口同時寫入到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端口
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.