分布式业务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

    

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