分佈式業務Redis安裝與集羣配置

 Redis在百度百科裏的解釋:Redis是一個開源的使用ANSI  C語言編寫、支持網絡、可基於內存亦可持久化的日誌型、Key-Value數據庫,並提供多種語言的API,包括C#、Java、PHP等等,甚至連Javascript都做了很好的封裝。


       可見Redis的數據是持久化的,可以分擔一個項目中的部分業務,Redis的數據是存儲在服務器內存當中的,這樣可以極大的加快訪問速度,因爲內存的讀取速度遠遠超過磁盤和數據庫,這在很大程序的上解決了大併發的困惑;同時Redis和Memcached不同,會按照設定的規律定期將數據同步到磁盤數據庫,這樣在Redis服務器宕機時也能保證數據的完整性。

       大家都知道Redis在全球最大的用戶是新浪微博,新浪有最大的Redis集羣,新浪最開始使用Memcached與Mysql配合,後來新浪又增加了Redis,而不是棄用Memcached,新浪加入Redis集羣的初衷:

      1、Memcached存在命中率問題,這樣大量請求會發送到Mysql,對於新浪微博這麼大的併發無疑是一個災難,Redis不存在命中率問題

      2、Redis相對於Memcached支持更多的數據類型,如string(字符串)、list(鏈表)、set(集合)、zset(有序集合)和hash(哈希類型)。這些數據類型都支持push/pop、add/remove及取交集並集和差集及更豐富的操作,而且這些操作都是原子性的

     3、Redis主從集羣配置技術容易實現,維護成本低,項目複雜度低

     4、Redis的持久化存儲從某種程度上解決了Cache宕機帶來的雪崩現象

       當然,新浪並沒有棄用Memcached+Mysql,用戶的全量信息是在此結構中的,使用Redis帶來的問題是,數據是持久化的,這是相當佔用內存的,成本不可小覷。

      Redis(2.8.19目前最新穩定版本)的安裝:

      1.下載:

          http://pan.baidu.com/s/1jGvJxBo

       2.安裝

        解壓下載文件:

        [root@jhq0229 src]# tar xzvf redis-stable.tar.gz
       

        編譯安裝:

        [root@jhq0229 src]# cd redis-stable


        [root@jhq0229 redis-stable]# make 


        [root@jhq0229 redis-stable]# make  PREFIX=/usr/local install

       

        配置:

        [root@jhq0229 redis-stable]# mkdir /etc/redis

       

        [root@jhq0229 redis-stable]# cp redis.conf /etc/redis/

       

         創建Redis數據及日誌存放目錄:

         [root@jhq0229 redis-stable]# mkdir /data/redis


         Redis配置文件詳解:

        

[plain] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. daemonize:如果需要在後臺運行,把該項心爲yes  
  2. pidfile:配置多個pid的地址,默認在/var/run/redis.pid  
  3. bind:綁定ip,設置後只接受來自該ip的請求  
  4. port:監聽端口,默認爲6379  
  5. timeout:設置客戶端連接時的超時時間,單位爲秒  
  6. loglevel:分爲4級,debug、verbose、notice、warning  
  7. logfile:配置log文件地址  
  8. databases:設置數據庫的個數,默認使用的數據庫爲0  
  9. save:設置redis進行數據庫鏡像的頻率  
  10. rdbcompression:在進行鏡像備份時,是否進行壓縮  
  11. Dbfilename:鏡像備份文件的文件名  
  12. Dir:數據庫鏡像備份的文件放置路徑  
  13. Slaveof:設置數據庫爲其他數據庫的從數據庫  
  14. Masterauth:主數據庫連接需要的密碼驗證  
  15. Requirepass:設置登錄登錄時需要使用的密碼  
  16. Maxclients:限制同時連接的客戶數量  
  17. Maxmemory:設置redis能夠使用的最大內存  
  18. Appendonly:開啓append only模式  
  19. Appendfsync:設置對appendonly.aof文件同步的頻率  
  20. vm-enabled:是否開啓虛擬內存支持  
  21. vm-swap-file:設置虛擬內存的交換文件路徑  
  22. vm-max-memory:設置redis使用的最大物理內存大小  
  23. vm-page-size:設置虛擬內存的頁大小  
  24. vm-pages:設置交換文件的總的page數量  
  25. vm-max-threads:設置VMIO同時使用的線程數量  
  26. Glueoutputbuf:把小的輸出緩存存放在一起  
  27. hash-max-zipmap-entries:設置hash的臨界值  
  28. Activerehashing:重新hash  


        配置自己的Redis集羣(若不配置集羣可以只配置Master):

       [root@jhq0229 redis-stable]# vim /etc/redis/redis.conf


        我的Redis主從配置:

        主:192.168.1.18              認證密碼:01130229

        從:192.168.1.16


        主Redis(Master)配置:

       

[plain] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. # Redis configuration file example  
  2.   
  3. # Note on units: when memory size is needed, it is possible to specify  
  4. # it in the usual form of 1k 5GB 4M and so forth:  
  5. #  
  6. # 1k => 1000 bytes  
  7. # 1kb => 1024 bytes  
  8. # 1m => 1000000 bytes  
  9. # 1mb => 1024*1024 bytes  
  10. # 1g => 1000000000 bytes  
  11. # 1gb => 1024*1024*1024 bytes  
  12. #  
  13. # units are case insensitive so 1GB 1Gb 1gB are all the same.  
  14.   
  15. ################################## INCLUDES ###################################  
  16.   
  17. # Include one or more other config files here.  This is useful if you  
  18. # have a standard template that goes to all Redis servers but also need  
  19. # to customize a few per-server settings.  Include files can include  
  20. # other files, so use this wisely.  
  21. #  
  22. # Notice option "include" won't be rewritten by command "CONFIG REWRITE"  
  23. # from admin or Redis Sentinel. Since Redis always uses the last processed  
  24. # line as value of a configuration directive, you'd better put includes  
  25. # at the beginning of this file to avoid overwriting config change at runtime.  
  26. #  
  27. # If instead you are interested in using includes to override configuration  
  28. # options, it is better to use include as the last line.  
  29. #  
  30. # include /path/to/local.conf  
  31. # include /path/to/other.conf  
  32.   
  33. ################################ GENERAL  #####################################  
  34.   
  35. # By default Redis does not run as a daemon. Use 'yes' if you need it.  
  36. # Note that Redis will write a pid file in /var/run/redis.pid when daemonized.  
  37. #是否以後臺進程方式運行  
  38. daemonize yes  
  39.   
  40. # When running daemonized, Redis writes a pid file in /var/run/redis.pid by  
  41. # default. You can specify a custom pid file location here.  
  42. #以後臺進行運行,需指定pid  
  43. pidfile /var/run/redis.pid  
  44.   
  45. # Accept connections on the specified port, default is 6379.  
  46. # If port 0 is specified Redis will not listen on a TCP socket.  
  47. port 6379  
  48.   
  49. # TCP listen() backlog.  
  50. #  
  51. # In high requests-per-second environments you need an high backlog in order  
  52. # to avoid slow clients connections issues. Note that the Linux kernel  
  53. # will silently truncate it to the value of /proc/sys/net/core/somaxconn so  
  54. # make sure to raise both the value of somaxconn and tcp_max_syn_backlog  
  55. # in order to get the desired effect.  
  56. tcp-backlog 511  
  57.   
  58. # By default Redis listens for connections from all the network interfaces  
  59. # available on the server. It is possible to listen to just one or multiple  
  60. # interfaces using the "bind" configuration directive, followed by one or  
  61. # more IP addresses.  
  62. #  
  63. # Examples:  
  64. #  
  65. # bind 192.168.1.100 10.0.0.1  
  66. bind 192.168.1.18  
  67.   
  68. # Close the connection after a client is idle for N seconds (0 to disable)  
  69. #客戶端閒置N秒後關閉連接  
  70. timeout 30  
  71.   
  72. tcp-keepalive 0  
  73.   
  74. # Specify the server verbosity level.  
  75. # This can be one of:  
  76. # debug (a lot of information, useful for development/testing)  
  77. # verbose (many rarely useful info, but not a mess like the debug level)  
  78. # notice (moderately verbose, what you want in production probably)  
  79. # warning (only very important / critical messages are logged)  
  80. #日誌級別  
  81. loglevel notice  
  82.   
  83. #記錄日誌的文件名稱  
  84. logfile "redlog"  
  85.   
  86. # To enable logging to the system logger, just set 'syslog-enabled' to yes,  
  87. # and optionally update the other syslog parameters to suit your needs.  
  88. # syslog-enabled no  
  89.   
  90. # Specify the syslog identity.  
  91. # syslog-ident redis  
  92.   
  93. # Specify the syslog facility. Must be USER or between LOCAL0-LOCAL7.  
  94. # syslog-facility local0  
  95.   
  96. # Set the number of databases. The default database is DB 0, you can select  
  97. # a different one on a per-connection basis using SELECT <dbid> where  
  98. # dbid is a number between 0 and 'databases'-1  
  99. #可用數據庫數量  
  100. databases 16  
  101.   
  102. ################################ SNAPSHOTTING  ################################  
  103. #  
  104. # Save the DB on disk:  
  105. #  
  106. #   save <seconds> <changes>  
  107. #  
  108. #   Will save the DB if both the given number of seconds and the given  
  109. #   number of write operations against the DB occurred.  
  110. #  
  111. #   In the example below the behaviour will be to save:  
  112. #   after 900 sec (15 min) if at least 1 key changed  
  113. #   after 300 sec (5 min) if at least 10 keys changed  
  114. #   after 60 sec if at least 10000 keys changed  
  115. #  
  116. #   Note: you can disable saving completely by commenting out all "save" lines.  
  117. #  
  118. #   It is also possible to remove all the previously configured save  
  119. #   points by adding a save directive with a single empty string argument  
  120. #   like in the following example:  
  121. #  
  122. #   save ""  
  123. #當有一條數據更新,900秒後同步數據到磁盤數據庫  
  124. save 900 1  
  125. #當有10條數據更新,300秒後同步數據到磁盤數據庫  
  126. save 300 10  
  127. save 60 10000  
  128.   
  129.   
  130. stop-writes-on-bgsave-error yes  
  131.   
  132. # Compress string objects using LZF when dump .rdb databases?  
  133. # For default that's set to 'yes' as it's almost always a win.  
  134. # If you want to save some CPU in the saving child set it to 'no' but  
  135. # the dataset will likely be bigger if you have compressible values or keys.  
  136. #當dump .rdb的時候是否壓縮數據對象,默認值爲yes  
  137. rdbcompression yes  
  138.   
  139. rdbchecksum yes  
  140.   
  141. # The filename where to dump the DB  
  142. # 磁盤數據庫文件名稱  
  143. dbfilename myredis.rdb  
  144.   
  145. #本地數據庫存放路徑  
  146. dir /data/redis/  
  147.   
  148. ################################# REPLICATION #################################  
  149. #Redis主從複製配置  
  150.   
  151. #若當前服務爲slave,在此處設置主服務的ip及端口  
  152. # slaveof <masterip> <masterport>  
  153.   
  154. #若當前服務爲slave,設置主服務的認證密碼  
  155. # masterauth <master-password>  
  156.   
  157.   
  158. slave-serve-stale-data yes  
  159.   
  160. #若當前爲slave服務,設置slave是否爲只讀服務  
  161. #slave-read-only yes  
  162.   
  163. # Replication SYNC strategy: disk or socket.  
  164. #  
  165. # -------------------------------------------------------  
  166. # WARNING: DISKLESS REPLICATION IS EXPERIMENTAL CURRENTLY  
  167. # -------------------------------------------------------  
  168. #  
  169. # New slaves and reconnecting slaves that are not able to continue the replication  
  170. # process just receiving differences, need to do what is called a "full  
  171. # synchronization". An RDB file is transmitted from the master to the slaves.  
  172. # The transmission can happen in two different ways:  
  173. #  
  174. # 1) Disk-backed: The Redis master creates a new process that writes the RDB  
  175. #                 file on disk. Later the file is transferred by the parent  
  176. #                 process to the slaves incrementally.  
  177. # 2) Diskless: The Redis master creates a new process that directly writes the  
  178. #              RDB file to slave sockets, without touching the disk at all.  
  179. #  
  180. # With disk-backed replication, while the RDB file is generated, more slaves  
  181. # can be queued and served with the RDB file as soon as the current child producing  
  182. # the RDB file finishes its work. With diskless replication instead once  
  183. # the transfer starts, new slaves arriving will be queued and a new transfer  
  184. # will start when the current one terminates.  
  185. #  
  186. # When diskless replication is used, the master waits a configurable amount of  
  187. # time (in seconds) before starting the transfer in the hope that multiple slaves  
  188. # will arrive and the transfer can be parallelized.  
  189. #  
  190. # With slow disks and fast (large bandwidth) networks, diskless replication  
  191. # works better.  
  192. repl-diskless-sync no  
  193.   
  194. repl-diskless-sync-delay 5  
  195.   
  196. # Slaves send PINGs to server in a predefined interval. It's possible to change  
  197. # this interval with the repl_ping_slave_period option. The default value is 10  
  198. # seconds.  
  199. #  
  200. # repl-ping-slave-period 10  
  201.   
  202.   
  203. # repl-timeout 60  
  204.   
  205. repl-disable-tcp-nodelay no  
  206.   
  207. slave-priority 100  
  208.   
  209. ################################## SECURITY ###################################  
  210.   
  211. # Require clients to issue AUTH <PASSWORD> before processing any other  
  212. # commands.  This might be useful in environments in which you do not trust  
  213. # others with access to the host running redis-server.  
  214. #  
  215. # This should stay commented out for backward compatibility and because most  
  216. # people do not need auth (e.g. they run their own servers).  
  217. #  
  218. # Warning: since Redis is pretty fast an outside user can try up to  
  219. # 150k passwords per second against a good box. This means that you should  
  220. # use a very strong password otherwise it will be very easy to break.  
  221. #認證密碼  
  222. requirepass 01130229  
  223.   
  224.   
  225. ################################### LIMITS ####################################  
  226.   
  227. # Set the max number of connected clients at the same time. By default  
  228. # this limit is set to 10000 clients, however if the Redis server is not  
  229. # able to configure the process file limit to allow for the specified limit  
  230. # the max number of allowed clients is set to the current file limit  
  231. # minus 32 (as Redis reserves a few file descriptors for internal uses).  
  232. #  
  233. # Once the limit is reached Redis will close all the new connections sending  
  234. # an error 'max number of clients reached'.  
  235.   
  236. # Don't use more memory than the specified amount of bytes.  
  237. # When the memory limit is reached Redis will try to remove keys  
  238. # according to the eviction policy selected (see maxmemory-policy).  
  239. #  
  240. # If Redis can't remove keys according to the policy, or if the policy is  
  241. # set to 'noeviction', Redis will start to reply with errors to commands  
  242. # that would use more memory, like SET, LPUSH, and so on, and will continue  
  243. # to reply to read-only commands like GET.  
  244. #  
  245. # This option is usually useful when using Redis as an LRU cache, or to set  
  246. # a hard memory limit for an instance (using the 'noeviction' policy).  
  247. #  
  248. # WARNING: If you have slaves attached to an instance with maxmemory on,  
  249. # the size of the output buffers needed to feed the slaves are subtracted  
  250. # from the used memory count, so that network problems / resyncs will  
  251. # not trigger a loop where keys are evicted, and in turn the output  
  252. # buffer of slaves is full with DELs of keys evicted triggering the deletion  
  253. # of more keys, and so forth until the database is completely emptied.  
  254. #  
  255. # In short... if you have slaves attached it is suggested that you set a lower  
  256. # limit for maxmemory so that there is some free RAM on the system for slave  
  257. # output buffers (but this is not needed if the policy is 'noeviction').  
  258. # maxmemory <bytes>  
  259.   
  260. # MAXMEMORY POLICY: how Redis will select what to remove when maxmemory  
  261. # is reached. You can select among five behaviors:  
  262. #  
  263. # volatile-lru -> remove the key with an expire set using an LRU algorithm  
  264. # allkeys-lru -> remove any key according to the LRU algorithm  
  265. # volatile-random -> remove a random key with an expire set  
  266. # allkeys-random -> remove a random key, any key  
  267. # volatile-ttl -> remove the key with the nearest expire time (minor TTL)  
  268. # noeviction -> don't expire at all, just return an error on write operations  
  269. #  
  270. # Note: with any of the above policies, Redis will return an error on write  
  271. #       operations, when there are no suitable keys for eviction.  
  272. #  
  273. #       At the date of writing these commands are: set setnx setex append  
  274. #       incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd  
  275. #       sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby  
  276. #       zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby  
  277. #       getset mset msetnx exec sort  
  278. #  
  279. # The default is:  
  280. #  
  281. # maxmemory-policy volatile-lru  
  282.   
  283. # LRU and minimal TTL algorithms are not precise algorithms but approximated  
  284. # algorithms (in order to save memory), so you can select as well the sample  
  285. #  
  286. # maxmemory-samples 3  
  287.   
  288. ############################## APPEND ONLY MODE ###############################  
  289.   
  290. # By default Redis asynchronously dumps the dataset on disk. This mode is  
  291. # good enough in many applications, but an issue with the Redis process or  
  292. # a power outage may result into a few minutes of writes lost (depending on  
  293. # the configured save points).  
  294. #  
  295. appendonly no  
  296.   
  297. # The name of the append only file (default: "appendonly.aof")#更新日誌文件名稱  
  298.   
  299. #  
  300. #  
  301. # If unsure, use "everysec".  
  302. # appendfsync always  
  303. appendfsync everysec  
  304. # appendfsync no  
  305.   
  306. no-appendfsync-on-rewrite no  
  307.   
  308. auto-aof-rewrite-percentage 100  
  309. auto-aof-rewrite-min-size 64mb  
  310.   
  311. aof-load-truncated yes  
  312.   
  313. ################################ LUA SCRIPTING  ###############################  
  314.   
  315. # Max execution time of a Lua script in milliseconds.  
  316. #  
  317. # If the maximum execution time is reached Redis will log that a script is  
  318. # still in execution after the maximum allowed time and will start to  
  319. # reply to queries with an error.  
  320. #  
  321. lua-time-limit 5000  
  322.   
  323. ################################## SLOW LOG ###################################  
  324.   
  325. # The Redis Slow Log is a system to log queries that exceeded a specified  
  326. # execution time. The execution time does not include the I/O operations  
  327. # like talking with the client, sending the reply and so forth,  
  328. # but just the time needed to actually execute the command (this is the only  
  329. # stage of command execution where the thread is blocked and can not serve  
  330. # other requests in the meantime).  
  331. slowlog-log-slower-than 10000  
  332.   
  333. slowlog-max-len 128  
  334.   
  335. ################################ LATENCY MONITOR ##############################  
  336.   
  337. # The Redis latency monitoring subsystem samples different operations  
  338. # at runtime in order to collect data related to possible sources of  
  339. # latency of a Redis instance.  
  340. #  
  341.   
  342. latency-monitor-threshold 0  
  343.   
  344. ############################# Event notification ##############################  
  345.   
  346.   
  347. notify-keyspace-events ""  
  348.   
  349. ############################### ADVANCED CONFIG ###############################  
  350.   
  351. # Hashes are encoded using a memory efficient data structure when they have a  
  352. # small number of entries, and the biggest entry does not exceed a given  
  353. # threshold. These thresholds can be configured using the following directives.  
  354. hash-max-ziplist-entries 512  
  355. hash-max-ziplist-value 64  
  356.   
  357. list-max-ziplist-entries 512  
  358. list-max-ziplist-value 64  
  359.   
  360. set-max-intset-entries 512  
  361.   
  362. zset-max-ziplist-entries 128  
  363. zset-max-ziplist-value 64  
  364.   
  365. hll-sparse-max-bytes 3000  
  366. activerehashing yes  
  367. client-output-buffer-limit normal 0 0 0  
  368. client-output-buffer-limit slave 256mb 64mb 60  
  369. client-output-buffer-limit pubsub 32mb 8mb 60  
  370. hz 10  
  371.   
  372. aof-rewrite-incremental-fsync yes  

      

       從Redis(Slave)配置,配置與Master類似,不一致內容如下:


[plain] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. #綁定IP地址  
  2. bind 192.168.1.16  
  3.   
  4. #若當前服務爲slave,在此處設置主服務的ip及端口  
  5. slaveof 192.168.1.18 6379  
  6.   
  7. #若當前服務爲slave,設置主服務的認證密碼  
  8. masterauth 01130229  

      配置Redis開機啓動:

     [root@jhq0229 redis-stable]# vim /etc/init.d/redis

     內容如下:

[plain] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. #!/bin/bash  
  2. #  
  3. # redis - this script starts and stops the redis-server daemon  
  4. #  
  5. # chkconfig:   - 80 12  
  6. # description:  Redis is a persistent key-value database  
  7. # processname: redis-server  
  8. # config:      /etc/redis/redis.conf  
  9. # pidfile:     /var/run/redis.pid  
  10.   
  11. source /etc/init.d/functions  
  12.   
  13. BIN="/usr/local/bin"  
  14. CONFIG="/etc/redis/redis.conf"  
  15. PIDFILE="/var/run/redis.pid"  
  16.   
  17.   
  18. ### Read configuration  
  19. [ -r "$SYSCONFIG" ] && source "$SYSCONFIG"  
  20.   
  21. RETVAL=0  
  22. prog="redis-server"  
  23. desc="Redis Server"  
  24.   
  25. start() {  
  26.   
  27.         if [ -e $PIDFILE ];then  
  28.              echo "$desc already running...."  
  29.              exit 1  
  30.         fi  
  31.   
  32.         echo -n $"Starting $desc: "  
  33.         daemon $BIN/$prog $CONFIG  
  34.   
  35.         RETVAL=$?  
  36.         echo  
  37.         [ $RETVAL -eq 0 ] && touch /var/lock/subsys/$prog  
  38.         return $RETVAL  
  39. }  
  40.   
  41. stop() {  
  42.         echo -n $"Stop $desc: "  
  43.         killproc $prog  
  44.         RETVAL=$?  
  45.         echo  
  46.         [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/$prog $PIDFILE  
  47.         return $RETVAL  
  48. }  
  49.   
  50. restart() {  
  51.     stop  
  52.     start  
  53. }  
  54.   
  55. case "$1" in  
  56.   start)  
  57.         start  
  58.         ;;  
  59.   stop)  
  60.         stop  
  61.         ;;  
  62.   restart)  
  63.         restart  
  64.         ;;  
  65.   condrestart)  
  66.         [ -e /var/lock/subsys/$prog ] && restart  
  67.         RETVAL=$?  
  68.         ;;  
  69.   status)  
  70.         status $prog  
  71.         RETVAL=$?  
  72.         ;;  
  73.    *)  
  74.         echo $"Usage: $0 {start|stop|restart|condrestart|status}"  
  75.         RETVAL=1  
  76. esac  
  77.   
  78. exit $RETVAL  

 

     [root@jhq0229 redis-stable]# chmod +x /etc/init.d/redis


     [root@jhq0229 redis-stable]# chkconfig redis on

 

     補充配置,配置停止服務前同步數據到磁盤:

     [root@jhq0229 redis-stable]# vim /etc/sysctl.conf

     進行如下修改:

     vm.overcommit_memory=1

     應用修改:

      sysctl -p

    

      啓動Redis:

      [root@jhq0229 redis-stable]# service redis start

     

      主從Redis的安裝和配置只是配置文件不同,其他的均一樣,一般主從配好就可以測試主從操作了,主server上set,從server馬上就可以get到了。


     最後,奉上公司同事辛勤總結的Redis學習資料。希望可以幫到你。

     下載地址:    http://pan.baidu.com/s/1qWLV87a

    

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章