NoSQL數據庫之redis持久化存儲(一)

第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特色

  1. key-value鍵值類型存儲
  2. 支持數據可靠存儲及落地
  3. 單進程單線程高性能服務器
  4. crash safe & recovery slow
  5. 單機qps能夠達到10W
  6. 適合小數據量高速讀寫訪問
 

1.3 Redis優勢

  1. 與memcached不一樣,Redis能夠持久化存儲數據
  2. 性能很高:Redis能支持超過10W每秒的讀寫頻率。
  3. 豐富的數據類型:Redis支持二進制的Strings,Lists,Hashes,Sets及sorted Sets等數據類型操做
  4. 原子:Redis的全部操做都是原子性的,同時Redis還支持對幾個操做全並後的原子性執行
  5. 豐富的特性:Redis還支持publish/subscribe(發佈/訂閱),通知,key過時等等特性。
  6. redis支持異機主從複製。
 

1.4 redis缺陷與陷阱

  1. 系統運行有毛刺
  2. 不一樣命令延遲差異極大
  3. 內存管理開銷大(設置低於物理內存3/5)
  4. buffer io形成系統OOM(內存溢出)
 

1.5 redis的數據類型

做爲Key-value型存儲系統數據庫,Redis提供了鍵(Key)和值(value)映射關係。可是,除了常規的數值或字符串,Redis的鍵值還能夠是如下形式之一,下面爲最爲經常使用的數據類型: 
- String 字符串 
- Hash 哈希表 
- List 列表 
- Set 集合 
- Sorted set 有序集合 
image_1crp45kuo7oj1cp5pmv19c81cpap.png-342kB
php

 

1.6 redis 持久化

一般,Redis將數據存儲於內存中,或被配置爲使用虛擬內存。經過兩種方式能夠實現數據持久化:使用快照(snapshot)的方式,將內存中的數據不斷寫入磁盤,或使用相似MySQL的binlog日誌(aof但並不用於主從同步)方式,記錄每次更新的日誌。前者性能較高,可是可能會引發必定程度的數據丟失;後者相反。 
image_1crp465n61dahqprpps1oa716al16.png-284.5kB
html

 
  1. #名詞解釋
  2. #Snapshot(快照)
  3. save 900 1 #900秒有1key容量被更新,則觸發快照寫入磁盤
  4. save 300 10
  5. save 60 10000
  6. #AOF(更新日誌)
  7. appendfsync always #老是記錄更新內容
  8. appendfsync everysec #每秒記錄更新內容
  9. appendfsync no #不記錄更新內容

image_1crp4m76cp0liqucfdlkib3o23.png-429.5kB

特別提示: 
若是選擇了快照的策略,那麼快照在每次進行保存的時候,都會阻礙執行前端的客戶端請求。 
快照會一次性將內存裏的數據全都寫進磁盤。
前端

 

1.7 redis的應用場景

(1)MySQL+Memcached網站架構問題python

經過MySQL數據庫存儲數據庫數據,加上經過Memcached把熱點數據存放到內存cache裏,達到加速數據訪問減輕數據庫壓力的目的,這是絕大部分公司都曾經使用過這樣的架構,但隨着業務數據量的不斷增長,和訪問量的持續增加,不少問題就會暴露出來:mysql

  1. 須要不斷的對MySQL進行拆庫拆表,Memcached也需不斷跟着擴容,擴容和維護工做佔據大量開發運維時間。
  2. Memcached與MySQL數據庫數據一致性問題是個老大難。
  3. Memcached數據命中率低或down機,會致使大量訪問直接穿透到數據庫,致使MySQL沒法支撐訪問。
  4. 跨機房cache同步及cache數據一致性問題

(2)redis的最佳應用場景linux

  1. Redis最佳試用場景是所有數據in-memory
  2. Redis更多場景是做爲Memcached的替代品來使用。
  3. 數據比較重要,對數據一致性有必定要求的業務。
  4. 當須要除key/value以外的更多數據類型支持時,使用Redis更合適。
  5. 須要提供主從同步以及負載均衡分佈式應用場景(redis主從同步)

更多git

a.Redis做者談Redis應用場景 
http://blog.nosqlfan.com/html/2235.html
github

b.使用Redis bitmap進行活躍用戶統計 
http://blog.nosqlfan.com/html/3501.html
web

  • 計數,cache服務,展現最近,最熱,點擊率最高,活躍度最高等等條件的top list,用戶最近訪問記錄,Relation List/Message Queue,粉絲列表。
  • Key-Value Store 更加註重對海量數據存取的性能,分佈式,擴展性支持上,並不須要傳統關係數據庫的一些特徵,例如:Schema,事務,完整SQL查詢支持等等,所以在分佈式環境下的性能相對於傳統的關係數據庫有較大提高。 
    image_1crp4piqt1g3ibk21f6d10aenf330.png-478.4kB 
    image_1crp4ptfp887hnc2ju2d71kl53t.png-512.9kB
 

1.8 redis的應用案例

sina使用redis案例:redis

(1)application -->redis

(2)應用程序首先訪問Redis,只有當Redis沒有數據或訪問失敗時訪問redis。

(3)二次開發實現MySQL和redis互相同步

MySQL -->Redis複製

  • 經過RBR解析BINLOG同步到redis
  • Redis提供特定數據結構的讀訪問
  • 實現關係型數據轉變成隊列數據

Redis -->MySQL複製

  • Redis提供特定數據結構的讀寫
  • 經過replication接口同時寫入到MySQ

新浪爲何用redis?

  1. 數據結構(Data Structure)需求愈來愈多,但Memcache中沒有,影響開發效率。
  2. 性能需求,隨着讀操做的量的上升須要解決,經歷的過程有:數據庫讀寫分離(M/S)-->數據庫使用多個Slave -->增長Cache(memcache)-->轉到Redis
  3. 解決寫的問題:水平拆分,對錶的拆分,將有的用戶放在這個表,有的用戶放在另一個表。
  4. 可靠性需求:Cache的「雪崩」問題讓人糾結;Cache面臨着快速恢復的挑戰。
  5. 開發成本需求:Cache和DB的一致性維護成本愈來愈高(先清理DB,再清理緩存,不行啊,太慢了!)開發須要跟上不斷涌入的產品需求,硬件成本最貴的就是數據庫層面的機器,基本上比前端的機器要貴幾倍,主要是IO密集型,很耗硬件。
  6. 維護性複雜:一致性維護成本愈來愈高。BerkeleyDB使用B樹,會一直寫新的,內部不會有文件從新組織;這樣會致使文件愈來愈大;大的時候須要進行文檔歸檔,歸檔的操做要按期作;這樣,就須要有必定的down time。

因此基於以上考慮,新浪選擇了Redis

 

1.9 Redis的生產經驗教訓

  1. 必定要進行Master-slave主從同步配置,在出現服務故障時能夠切換
  2. 在master禁用數據持久化,只須要在slave上配置數據持久化
  3. 物理內存+虛擬內存不足,這個時候dump一直死着,時間久了機器掛掉。這個狀況就是災難!
  4. 當Redis物理內存使用超過內存總容量的3/5時就會開始比較危險了,就開始作swap,內存碎片大!
  5. 當達到最大內存時,會清空帶有過時時間的key,即便key未到過時時間。
  6. redis與DB同步寫的問題,先寫DB,後寫redis,由於寫內存基本上沒有問題。
 

第2章 快速部署一個redis環境

 

2.1 Redis部署環境搭建

image_1crp4u1t56ga9q0p5a1hun2k14a.png-4.3kB

 

2.2 開始安裝redis服務

在redis的官方網站(http://www.redis.io)下載最新的穩定版本redis。

 
  1. wget -q http://download.redis.io/releases/redis-2.8.9.tar.gz
  2. #在redis01和redis02都執行以下操做
  3. [root@redis01 ~]# tar xf redis-2.8.9.tar -C /usr/src/
  4. [root@redis01 ~]# cd /usr/src/redis-2.8.9/
  5. [root@redis01 redis-2.8.9]# make MALLOC=jemalloc
  6. [root@redis01 redis-2.8.9]# make PREFIX=/usr/local/redis install
  7. [root@redis01 redis-2.8.9]# LANG=en
  8. [root@redis01 redis-2.8.9]# tree /usr/local/redis/bin/
  9. /usr/local/redis/bin/
  10. ├── redis-benchmark
  11. ├── redis-check-aof
  12. ├── redis-check-dump
  13. ├── redis-cli
  14. └── redis-server
  15. 0 directories, 5 files

命令執行完成以後,會在/usr/local/redis/bin/目錄下生成5個可執行文件,分別是:

redis-server,redis-cli,redis-benchmark,redis-check-aof,redis-check-dump

它們的做用以下:

 
  1. redis-server #Redis服務器的daemon啓動程序
  2. redis-cli #Redis命令操做工具。固然,你也能夠用telnet根據其純文本協議來操做
  3. redis-benchmark #Redis性能測試工具,測試Redis在你的系統及你的配置下的讀寫性能。
  4. redis-check-aof #對更新日誌appendonly.aof檢查,是否可用,相似檢查mysql binlog的工具
  5. redis-check-dump #用於本地數據庫rdb文件的檢查
 

2.3 配置並啓動redis服務

(1)配置啓動命令

操做過程:

[root@redis01 redis-2.8.9]# ln -s /usr/local/redis/bin/* /usr/local/bin/

(2)查看命令幫助:

 
  1. [root@redis01 redis-2.8.9]# redis-server -h
  2. Usage: ./redis-server [/path/to/redis.conf] [options]
  3. ./redis-server - (read config from stdin)
  4. ./redis-server -v or --version
  5. ./redis-server -h or --help
  6. ./redis-server --test-memory <megabytes>
  7. Examples:
  8. ./redis-server (run the server with default conf)
  9. ./redis-server /etc/redis/6379.conf
  10. ./redis-server --port 7777
  11. ./redis-server --port 7777 --slaveof 127.0.0.1 8888
  12. ./redis-server /etc/myredis.conf --loglevel verbose
  13. Sentinel mode:
  14. ./redis-server /etc/sentinel.conf --sentinel

(3)啓動redis服務

操做過程:

 
  1. #從源程序目錄複製redis.conf到程序安裝目錄下
  2. [root@redis01 redis-2.8.9]# cd /usr/src/redis-2.8.9/
  3. [root@redis01 redis-2.8.9]# pwd
  4. /usr/src/redis-2.8.9
  5. [root@redis01 redis-2.8.9]# mkdir /usr/local/redis/conf
  6. [root@redis01 redis-2.8.9]# cp redis.conf /usr/local/redis/conf/
  7. #啓動redis服務
  8. [root@redis01 redis-2.8.9]# redis-server /usr/local/redis/conf/redis.conf &
  9. #查看redis進程啓動狀況
  10. [root@redis01 redis-2.8.9]# ps -ef | grep redis | grep -v grep
  11. root 3169 1288 0 10:17 pts/0 00:00:00 redis-server *:6379

特別提示: 
redis啓動成功後,在最後會出現以下警示信息:

 
  1. [3169] 02 Oct 10:17:30.689 # Server started, Redis version 2.8.9
  2. [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.
  3. [3169] 02 Oct 10:17:30.690 * The server is now ready to accept connections on port 6379
  4. #警示大概意思爲:
  5. overcommit_memory被設置爲了0.若是內存不夠的狀況下後臺保存可能會失敗;要解決這個問題,須要在/etc/sysctl.conf配置文件中將vm.overcommit_memory設置爲1;或者經過命令「sysctl vm.overcommit_memory=1」來修改。

所以,咱們作一下處理後在啓動redis進程

 
  1. [root@redis01 redis-2.8.9]# pkill redis
  2. [root@redis01 redis-2.8.9]# sysctl vm.overcommit_memory=1
  3. vm.overcommit_memory = 1
  4. [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進程

 
  1. [root@redis01 redis-2.8.9]# ps -ef | grep redis | grep -v grep
  2. root 3200 1288 0 10:38 pts/0 00:00:08 redis-server *:6379
  3. [root@redis01 redis-2.8.9]# redis-cli shutdown
  4. [3200] 02 Oct 12:43:46.621 # User requested shutdown...
  5. [3200] 02 Oct 12:43:46.621 * Saving the final RDB snapshot before exiting.
  6. [3200] 02 Oct 12:43:46.630 * DB saved on disk
  7. [3200] 02 Oct 12:43:46.631 # Redis is now ready to exit, bye bye...
  8. [1]+ Done redis-server /usr/local/redis/conf/redis.conf
  9. [root@redis01 redis-2.8.9]# ps -ef | grep redis | grep -v grep
  10. [root@redis01 redis-2.8.9]# redis-server /usr/local/redis/conf/redis.conf
 

2.4 經過客戶端操做redis數據庫

下面咱們來簡單操做一下數據庫。 
插入數據:設置一個key-value對

 
  1. [root@redis01 redis-2.8.9]# redis-cli #經過客戶端鏈接本地redis
  2. 127.0.0.1:6379> set id 001 #寫入一條數據key(id),value(001)
  3. OK
  4. 127.0.0.1:6379> get id #取值key(id)
  5. "001" #顯示key對應的值
  6. 127.0.0.1:6379> del id #刪除key(id)
  7. (integer) 1 #1表示成功
  8. 127.0.0.1:6379> exists id #驗證key是否存在
  9. (integer) 0 #0表示不存在
  10. 127.0.0.1:6379> get id #取key的值
  11. (nil) #報錯信息
  12. 127.0.0.1:6379> set user001 benet
  13. OK
  14. 127.0.0.1:6379> set user002 yunjisuan
  15. OK
  16. 127.0.0.1:6379> set user003 yun123
  17. OK
  18. 127.0.0.1:6379> get user001
  19. "benet"
  20. 127.0.0.1:6379> get user002
  21. "yunjisuan"
  22. 127.0.0.1:6379> keys * #查看redis裏全部的key
  23. 1) "user003"
  24. 2) "user002"
  25. 3) "user001"
 

2.5 更多操做方式及命令幫助

(1)redis數據庫的表模式

 
  1. 127.0.0.1:6379> keys * #查看全部key
  2. 1) "user003"
  3. 2) "user002"
  4. 3) "user001"
  5. 127.0.0.1:6379> select 1 #切換到表1模式
  6. OK
  7. 127.0.0.1:6379[1]> keys * #查詢全部key
  8. (empty list or set) #什麼都沒有
  9. 127.0.0.1:6379[1]> set name wangwu #寫入一個key-value對
  10. OK
  11. 127.0.0.1:6379[1]> keys * #查看全部key
  12. 1) "name" #key(name)已經有了
  13. 127.0.0.1:6379[1]> get name #查看key(name)的值
  14. "wangwu"
  15. 127.0.0.1:6379[1]> select 0 #切換回表0模式(初始模式)
  16. OK
  17. 127.0.0.1:6379> keys * #查看全部key
  18. 1) "user003"
  19. 2) "user002"
  20. 3) "user001"

(2)redis-cli客戶端的遠程鏈接及非交互式操做數據庫

 
  1. [root@redis01 redis-2.8.9]# redis-cli -h 10.0.0.135 -p 6379
  2. 10.0.0.135:6379> quit
  3. [root@redis01 redis-2.8.9]# redis-cli -h 10.0.0.135 -p 6379 set aaa 111
  4. OK
  5. [root@redis01 redis-2.8.9]# redis-cli -h 10.0.0.135 -p 6379 get aaa
  6. "111"

(3)經過telnet鏈接redis數據庫

telnet 10.0.0.135 6379

 

2.6 redis命令幫助

(1)redis-cli客戶端命令幫助:

 
  1. 10.0.0.135:6379> ? #查看幫助命令用法
  2. redis-cli 2.8.9
  3. Type: "help @<group>" to get a list of commands in <group>
  4. "help <command>" for help on <command>
  5. "help <tab>" to get a list of possible help topics
  6. "quit" to exit
  7. 10.0.0.135:6379> help #查看幫助命令用法
  8. redis-cli 2.8.9
  9. Type: "help @<group>" to get a list of commands in <group>
  10. "help <command>" for help on <command>
  11. "help <tab>" to get a list of possible help topics
  12. "quit" to exit
  13. 10.0.0.135:6379> help set #查看set命令用法
  14. SET key value [EX seconds] [PX milliseconds] [NX|XX]
  15. summary: Set the string value of a key
  16. since: 1.0.0
  17. group: string
  18. 10.0.0.135:6379>

(2)經過help命令來查找命令

 
  1. #輸入help + 空格 + 屢次<Tab>鍵來切換全部命令
  2. 10.0.0.135:6379> help @generic #這裏須要狂按Tab鍵
 

2.7 redis安全

(1)爲redis客戶端設置外部連接密碼

警告:

由於redis速度至關快,因此在一臺比較好的服務器下,一個外部的用戶能夠在1秒內進行上萬次的密碼嘗試,這意味着你須要指定很是很是強大的密碼來防止暴力破解。

 
  1. [root@redis01 redis-2.8.9]# grep -n requirepass /usr/local/redis/conf/redis.conf #修改redis配置文件,添加密碼
  2. 198:# If the master is password protected (using the "requirepass" configuration
  3. 339:# requirepass foobared
  4. [root@redis01 redis-2.8.9]# sed -i '339 s@# requirepass foobared@requirepass yunjisuan@g' #密碼是yunjisuan /usr/local/redis/conf/redis.conf
  5. [root@redis01 redis-2.8.9]# grep -n requirepass /usr/local/redis/conf/redis.conf
  6. 198:# If the master is password protected (using the "requirepass" configuration
  7. 339:requirepass yunjisuan

重啓redis後測試

 
  1. #重啓redis進程
  2. [root@redis01 redis-2.8.9]# ps -ef | grep redis | grep -v grep
  3. root 3442 1288 0 13:40 pts/0 00:00:17 redis-server *:6379
  4. [root@redis01 redis-2.8.9]# redis-cli shutdown
  5. [3442] 02 Oct 18:17:03.370 # User requested shutdown...
  6. [3442] 02 Oct 18:17:03.370 * Saving the final RDB snapshot before exiting.
  7. [3442] 02 Oct 18:17:03.380 * DB saved on disk
  8. [3442] 02 Oct 18:17:03.380 # Redis is now ready to exit, bye bye...
  9. [1]+ Done redis-server /usr/local/redis/conf/redis.conf
  10. [root@redis01 redis-2.8.9]# ps -ef | grep redis | grep -v grep
  11. [root@redis01 redis-2.8.9]# redis-server /usr/local/redis/conf/redis.conf &
  12. [root@redis01 redis-2.8.9]# ps -ef | grep redis | grep -v grep
  13. root 3843 1288 0 18:18 pts/0 00:00:00 redis-server *:6379
  14. #測試驗證效果
  15. #第一種登錄驗證方式
  16. [root@redis01 redis-2.8.9]# redis-cli #登錄本地redis
  17. 127.0.0.1:6379> set name 3333 #存數據
  18. (error) NOAUTH Authentication required. #沒有驗證權限
  19. 127.0.0.1:6379> keys * #查看全部key
  20. (error) NOAUTH Authentication required. #沒有驗證權限
  21. 127.0.0.1:6379> auth yunjisuan #提交驗證密碼
  22. OK #驗證經過
  23. 127.0.0.1:6379> keys * #查看全部keys
  24. 1) "user003"
  25. 2) "ab"
  26. 3) "user002"
  27. 4) "aaa"
  28. 5) "user001"
  29. #第二種登陸驗證方式
  30. [root@redis01 redis-2.8.9]# redis-cli -a yunjisuan #登錄時提交密碼
  31. 127.0.0.1:6379> keys *
  32. 1) "user003"
  33. 2) "ab"
  34. 3) "user002"
  35. 4) "aaa"
  36. 5) "user001"

特別提示: 
redis沒有用戶的概念,只能設置鏈接密碼,而且redis的鏈接速度很是快。所以密碼須要設置的很複雜才安全。

 

(2)將危險的命令更名

 
  1. #查看配置文件說明
  2. [root@redis01 redis-2.8.9]# cat -n /usr/local/redis/conf/redis.conf | sed -n '326,359p'
  3. 326 ################################## SECURITY ###################################安全相關
  4. 327
  5. 328 # Require clients to issue AUTH <PASSWORD> before processing any other
  6. 329 # commands. This might be useful in environments in which you do not trust
  7. 330 # others with access to the host running redis-server.
  8. 331 #
  9. 332 # This should stay commented out for backward compatibility and because most
  10. 333 # people do not need auth (e.g. they run their own servers).
  11. 334 #
  12. 335 # Warning: since Redis is pretty fast an outside user can try up to
  13. 336 # 150k passwords per second against a good box. This means that you should
  14. 337 # use a very strong password otherwise it will be very easy to break.
  15. 338 #
  16. 339 requirepass yunjisuan ##添加的密碼驗證
  17. 340
  18. 341 # Command renaming.
  19. 342 #
  20. 343 # It is possible to change the name of dangerous commands in a shared
  21. 344 # environment. For instance the CONFIG command may be renamed into something
  22. 345 # hard to guess so that it will still be available for internal-use tools
  23. 346 # but not available for general clients.
  24. 347 #
  25. 348 # Example:
  26. 349 #
  27. 350 # rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52
  28. 351 #
  29. 352 # It is also possible to completely kill a command by renaming it into
  30. 353 # an empty string:
  31. 354 #
  32. 355 # rename-command CONFIG "" ##命令修改示例
  33. 356 #
  34. 357 # Please note that changing the name of commands that are logged into the
  35. 358 # AOF file or transmitted to slaves may cause problems.
  36. 359
  37. #修改配置文件
  38. [root@redis01 redis-2.8.9]# sed -i '359i rename-command set "sset"' /usr/local/redis/conf/redis.conf
  39. [root@redis01 redis-2.8.9]# sed -n '359p' /usr/local/redis/conf/redis.conf
  40. rename-command set "sset"
  41. #重啓redis進程
  42. [root@redis01 redis-2.8.9]# redis-cli -a yunjisuan shutdown
  43. [3843] 02 Oct 18:56:54.245 # User requested shutdown...
  44. [3843] 02 Oct 18:56:54.245 * Saving the final RDB snapshot before exiting.
  45. [3843] 02 Oct 18:56:54.255 * DB saved on disk
  46. [3843] 02 Oct 18:56:54.255 # Redis is now ready to exit, bye bye...
  47. [1]+ Done redis-server /usr/local/redis/conf/redis.conf
  48. [root@redis01 redis-2.8.9]# redis-server /usr/local/redis/conf/redis.conf &
  49. #驗證命令更名效果
  50. [root@redis01 redis-2.8.9]# redis-cli -a yunjisuan
  51. 127.0.0.1:6379> set xxx 555 #命令輸入錯誤(由於修改過了)
  52. (error) ERR unknown command 'set'
  53. 127.0.0.1:6379> sset xxx 555 #寫入key-value正確
  54. OK
  55. 127.0.0.1:6379> get xxx
  56. "555"
 

2.8 爲php安裝redis客戶端擴展

(1)獲取源碼包

wget https://github.com/nicolasff/phpredis/archive/master.zip

(2)安裝

 
  1. [root@redis01 ~]# ls -l phpredis-master.tar.gz
  2. -rw-r--r--. 1 root root 164509 Oct 2 19:23 phpredis-master.tar.gz
  3. [root@redis01 ~]# tar xf phpredis-master.tar.gz -C /usr/src/
  4. [root@redis01 ~]# cd /usr/src/phpredis-master/
  5. [root@redis01 phpredis-master]# /usr/local/php/bin/phpize
  6. [root@redis01 phpredis-master]# ./configure --with-php-config=/usr/local/php/bin/php-config
  7. [root@redis01 phpredis-master]# make && make install

(3)修改php.ini設置,重啓php

 
  1. #添加
  2. echo "extension = redis.so" >> /usr/local/php/lib/php.ini
  3. #將php.ini配置文件中的extension_dir修改爲以下:
  4. extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/"

image_1crp570iv142d10nt17j81qp71o2l4n.png-62.1kB

 

2.9 開發php程序操做redis

在操做以前,請將以前redis配置文件裏修改的redis命令註釋掉

 
  1. [root@redis01 scripts]# cat redis.php
  2. #!/bin/bash
  3. <?php
  4. $redis = new Redis();
  5. $redis -> connect("10.0.0.135",6379);
  6. $redis -> auth("yunjisuan");
  7. $redis -> set("name","yunjisuan");
  8. $var = $redis -> get("name");
  9. echo "$var\n";
  10. ?>
 

2.10 安裝Python redis客戶端操做redis

 
  1. wget https://pypi.python.org/packages/source/r/redis/redis-2.10.1.tar.gz
  2. tar xf redis-2.10.1.tar.gz
  3. cd redis-2.10.1
  4. python setup.py install

開發python程序操做redis

在操做前請將以前redis配置文件裏修改的redis命令註釋掉,不然報錯

 
  1. [root@redis01 redis-2.10.1]# python
  2. Python 2.6.6 (r266:84292, Nov 22 2013, 12:16:22)
  3. [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
  4. Type "help", "copyright", "credits" or "license" for more information.
  5. >>> import redis #引用redis支持庫
  6. >>> r = redis.Redis(host='10.0.0.135',port='6379',password='yunjisuan') #創建redis數據庫的鏈接對象(面向對象方式)
  7. >>> r.set('name','benet') #操做對象調用set方法寫入數據
  8. True
  9. >>> r.get('name') #操做對象調用get方式讀取數據
  10. 'benet'
  11. >>> r.dbsize() #操做對象查看redis數據庫的數據條數
  12. 1L
  13. >>> r.keys() #查看全部的key
  14. ['name']
  15. >>> exit() #退出
 

2.11 經過Web界面鏈接Python程序展現redis

開發Python腳本

 
  1. [root@redis01 scripts]# cat python-redis.py
  2. #/usr/bin/python
  3. from wsgiref.simple_server import make_server
  4. import redis
  5. def get_redis():
  6. r = redis.Redis(host='10.0.0.135',port='6379',password='yunjisuan',db=0)
  7. r.set('name','yunyunyun')
  8. return r.get('name')
  9. def hello_world_app(environ,start_response):
  10. status = '200 OK' #HTTP Status
  11. headers = [('Content-type','text/plain')] #HTTP Headers
  12. start_response(status,headers)
  13. # The returned object is going to be printed
  14. return get_redis()
  15. httpd = make_server('',8000,hello_world_app)
  16. print "Serving on port 8000..."
  17. # Server until process is killed
  18. httpd.serve_forever()

啓動python腳本

注意關閉iptables

 
  1. [root@redis01 scripts]# python python-redis.py
  2. Serving on port 8000... #監聽8000端口

經過客戶端瀏覽器鏈接Python程序 
image_1crp59n3gb0d18vl1guh1fammq054.png-29.8kB

 

2.12 解讀redis默認配置文件

 
    1. #redis支持include功能
    2. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '30,31p'
    3. 30 # include /path/to/local.conf
    4. 31 # include /path/to/other.conf
    5. #redis是否後臺運行
    6. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '37p'
    7. 37 daemonize no
    8. #pid號保存文件的位置
    9. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '41p'
    10. 41 pidfile /var/run/redis.pid
    11. #redis默認監聽端口
    12. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '45p'
    13. 45 port 6379
    14. #調整tcp監聽隊列
    15. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '54p'
    16. 54 tcp-backlog 511
    17. #調整redis的監聽地址
    18. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '63,64p'
    19. 63 # bind 192.168.1.100 10.0.0.1
    20. 64 # bind 127.0.0.1
    21. #調整客戶端超時時間
    22. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '74p'
    23. 74 timeout 0
    24. #調整tcp的會話保持時間
    25. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '90p'
    26. 90 tcp-keepalive 0
    27. #調整日誌級別
    28. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '98p'
    29. 98 loglevel notice
    30. #redis日誌記錄位置,默認是打印到屏幕上
    31. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '103p'
    32. 103 logfile ""
    33. #是否啓用syslog來接收日誌(好比日誌集中收集)
    34. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '113p'
    35. 113 # syslog-facility local0
    36. #設置數據庫的數量,若是缺省,默認爲0(select0...select 15)
    37. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '118p'
    38. 118 databases 16
    39. #redis快照設置
    40. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '120,144p'
    41. 120 ################################ SNAPSHOTTING ################################
    42. 121 #
    43. 122 # Save the DB on disk:
    44. 123 #
    45. 124 # save <seconds> <changes>
    46. 125 #
    47. 126 # Will save the DB if both the given number of seconds and the given
    48. 127 # number of write operations against the DB occurred.
    49. 128 #
    50. 129 # In the example below the behaviour will be to save:
    51. 130 # after 900 sec (15 min) if at least 1 key changed
    52. 131 # after 300 sec (5 min) if at least 10 keys changed
    53. 132 # after 60 sec if at least 10000 keys changed
    54. 133 #
    55. 134 # Note: you can disable saving at all commenting all the "save" lines.
    56. 135 #
    57. 136 # It is also possible to remove all the previously configured save
    58. 137 # points by adding a save directive with a single empty string argument
    59. 138 # like in the following example:
    60. 139 #
    61. 140 # save "" #若是不想保存在磁盤,就如此設置
    62. 141
    63. 142 save 900 1 #900秒內至少1key數據變化,但會阻塞用戶請求,高併發時不用
    64. 143 save 300 10 #300秒內至少10key數據變化,但會阻塞用戶請求,高併發時不用
    65. 144 save 60 10000 #60秒內至少10000key數據變化,但會阻塞用戶請求,高併發時不用
    66. #若是bgsave出錯是否中止寫入
    67. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '159p'
    68. 159 stop-writes-on-bgsave-error yes
    69. #redis將數據存儲在磁盤的什麼位置
    70. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '177p'
    71. 177 dbfilename dump.rdb
    72. #指定redis配置文件當前工做的路徑(指定dbfilename的當前路徑位置)
    73. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '187p'
    74. 187 dir ./
    75. #給redis設定密碼
    76. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '339p'
    77. 339 requirepass yunjisuan
    78. #修改redis操做命令的名稱
    79. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '355,357p'
    80. 355 # rename-command CONFIG ""
    81. 356 # rename-command set ""
    82. 357 # rename=command get yunjisuan
    83. #設定redis內存限制(可是內存用完後,redis就會開始刪除key)
    84. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '398p'
    85. 398 # maxmemory <bytes>
    86. #設定redis內存清理的算法
    87. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '403,408p'
    88. 403 # volatile-lru -> remove the key with an expire set using an LRU algorithm
    89. 404 # allkeys-lru -> remove any key accordingly to the LRU algorithm
    90. 405 # volatile-random -> remove a random key with an expire set
    91. 406 # allkeys-random -> remove a random key, any key
    92. 407 # volatile-ttl -> remove the key with the nearest expire time (minor TTL)
    93. 408 # noeviction -> don't expire at all, just return an error on write operations
    94. #設定redis內存限制及內存清理的算法示例
    95. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '421p'
    96. 421 # maxmemory-policy volatile-lru
    97. #關於redis的流模式的存儲說明
    98. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '431,449p'
    99. 431 ############################## APPEND ONLY MODE ###############################
    100. 432
    101. 433 # By default Redis asynchronously dumps the dataset on disk. This mode is
    102. 434 # good enough in many applications, but an issue with the Redis process or
    103. 435 # a power outage may result into a few minutes of writes lost (depending on
    104. 436 # the configured save points).
    105. 437 #
    106. 438 # The Append Only File is an alternative persistence mode that provides
    107. 439 # much better durability. For instance using the default data fsync policy
    108. 440 # (see later in the config file) Redis can lose just one second of writes in a
    109. 441 # dramatic event like a server power outage, or a single write if something
    110. 442 # wrong with the Redis process itself happens, but the operating system is
    111. 443 # still running correctly.
    112. 444 #
    113. 445 # AOF and RDB persistence can be enabled at the same time without problems.
    114. 446 # If the AOF is enabled on startup Redis will load the AOF, that is the file
    115. 447 # with the better durability guarantees.
    116. 448 #
    117. 449 # Please check http://redis.io/topics/persistence for more information.
    118. #是否啓用AOF存儲模式
    119. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '451p'
    120. 451 appendonly no
    121. #設定AOF文件的存儲位置
    122. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '455p'
    123. 455 appendfilename "appendonly.aof" #並不用於主從同步,只是redis在啓動時,讀取此文件用於恢復數據
    124. #設定AOF同步存儲的時間週期
    125. [root@redis01 scripts]# cat -n /usr/local/redis/conf/redis.conf | sed -n '481p'
    126. 481 appendfsync everysec #每秒或不用
相關文章
相關標籤/搜索