Redis学习笔记

转自:http://blog.leanote.com/post/chenmingjun/day67_Redis%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0

课程计划

  • 1、Redis的介绍 
    • a) 什么是NoSql
    • b) NoSql的分类
    • c) 什么是Redis
    • d) Redis的历史发展
    • e) Redis的应用场景
  • 2、Redis服务端的安装(重点)
  • 3、Redis客户端的使用 
    • a) redis自带客户端(命令行)
    • b) 图形界面的客户端(了解)
    • c) Java客户端Jedis(重点)
  • 4、Redis的数据类型(重点) 
    • a) String类型
    • b) 散列类型(Map类型)
    • c) List类型(列表类型)
    • d) Set类型(集合类型)
    • e) SortedSet类型(zset类型)
  • 5、keys命令(了解)
  • 6、Redis的持久化方案 
    • a) RDB方式(默认)
    • b) AOF方式
  • 7、Redis的主从复制
  • 8、Redis的集群(重点)
  • 9、Jedis连接Redis集群

1、Redis的介绍

1.1、什么是NoSql

为了解决高并发、高可扩展、高可用、大数据存储问题而产生的数据库解决方案,就是NoSql数据库。 
NoSQL,泛指非关系型的数据库,NoSQL即Not-Only SQL,它可以作为关系型数据库的良好补充

1.2、Nosql的分类

键值(Key-Value)存储数据库: 
  相关产品:Tokyo Cabinet/Tyrant、Redis、Voldemort、Berkeley DB 
  典型应用:内容缓存,主要用于处理大量数据的高访问负载 
  数据模型:一系列键值对 
  优势:快速查询 
  劣势:存储的数据缺少结构化(现在通过Redis数据类型得到解决) 
列存储数据库: 
  相关产品:Cassandra、HBase、Riak 
  典型应用:分布式的文件系统 
  数据模型:以列簇式存储,将同一列数据存在一起 
  优势:查找速度快,可扩展性强,更容易进行分布式扩展 
  劣势:功能相对局限 
文档型数据库: 
  相关产品:CouchDB、MongoDB 
  典型应用:Web应用(与Key-Value类似,Value是结构化的),比如:存储日志 
  数据模型:一系列键值对 
  优势:数据结构要求不严格 
  劣势:查询性能不高,而且缺乏统一的查询语法 
图形(Graph)数据库: 
  相关数据库:Neo4J、InfoGrid、Infinite Graph 
  典型应用:社交网络、微信平台 
  数据模型:图结构 
  优势:利用图结构相关算法。 
  劣势:需要对整个图做计算才能得出结果,不容易做分布式的集群方案。

1.3、什么是Redis

  Redis是用C语言开发的一个开源的高性能键值对(key-value)数据库。它通过提供多种键值数据类型来适应不同场景下的存储需求,目前为止Redis支持的键值数据类型如下: 
  String字符串类型 
  Map散列类型 
  List列表类型 
  Set集合类型 
  SortedSet有序集合类型

1.4、Redis的历史发展

  2008年,意大利的一家创业公司Merzia推出了一款基于MySQL的网站实时统计系统LLOOGG,然而没过多久该公司的创始人Salvatore Sanfilippo便对MySQL的性能感到失望,于是他决定亲自为LLOOGG量身定做一个数据库,并于2009年开发完成,这个数据库就是Redis。不过Salvatore Sanfilippo并不满足只将Redis用于LLOOGG这一款产品,而是希望更多的人使用它,于是在同一年Salvatore Sanfilippo将Redis开源发布,并开始和Redis的另一名主要的代码贡献者Pieter Noordhuis一起继续着Redis的开发,直到今天。 
  Salvatore Sanfilippo自己也没有想到,短短的几年时间,Redis就拥有了庞大的用户群体。Hacker News在2012年发布了一份数据库的使用情况调查,结果显示有近12%的公司在使用Redis。国内如新浪微博、街旁网、知乎网,国外如GitHub、Stack Overflow、Flickr等都是Redis的用户。 
  VMware公司从2010年开始赞助Redis的开发,Salvatore Sanfilippo和Pieter Noordhuis也分别在3月和5月加入VMware,全职开发Redis。

1.5、Redis的应用场景

  1、缓存(数据查询、短连接、新闻内容、商品内容等等)。(最多使用) 
  2、分布式集群架构中的session分离。 
  3、聊天室的在线好友列表。 
  4、任务队列。(秒杀、抢购、12306等等) 
  5、应用排行榜。 
  6、网站访问统计。 
  7、数据过期处理(可以精确到毫秒)。

2、Redis服务端的安装(重点)

2.1、Redis的下载

2.2、Redis的安装

Redis是C语言开发,建议在linux上运行,本教程使用Centos7作为安装环境。

  • 第一步:在VMware中安装CentOS7(参考Linux教程中的安装虚拟机)
  • 第二步:在Linux下安装gcc环境(该步骤可以省略,CentOS中默认自带C环境),但是建议还是手动安装下,需要联网,安装命令如下: 
      [root@itheima ~]# yum install gcc-c++ 
    安装成功截图: 
  • 第三步:将下载的Redis源码包上传到Linux服务器中 
    【注意:SecureCRT需要切换到sftp窗口,步骤:选中连接窗口右键“连接SFTP会话”,直接拖拽文件至窗口中,回车】 
      sftp> put -r “E:\学习资料\java\java就业班\17、第十七阶段redis(1天)\redis\res\redis-3.0.0.tar.gz” 
  • 第四步:返回到连接窗口,解压缩redis源码包 
      [root@itheima ~]# tar -zxf redis-3.0.0.tar.gz
  • 第五步:编译redis源码 
      [root@itheima ~]# cd redis-3.0.0/ 
      [root@itheima redis-3.0.0]# make
  • 第六步:安装redis 
      [root@itheima redis-3.0.0]# make install PREFIX=/usr/local/redis
  • 第七步:查看是否安装成功 
      [root@itheima redis-3.0.0]# cd /usr/local/redis/ 
      [root@itheima redis]# ll 

2.3、Redis的启动

2.3.1、前端启动

  • 前端启动的命令: 
      [root@itheima bin]# ./redis-server
  • 前端启动的关闭命令: 
      强制关闭(非法关闭):Ctrl+c 
      正常关闭(需要通过其他窗口):[root@itheima bin]# ./redis-cli shutdown
  • 启动界面: 
  • 前端启动的问题: 
      ssh命令窗口关闭,则redis-server程序结束,即一旦客户端关闭,则redis服务也停掉。不推荐使用此方法。

2.3.1、后端启动

  • 第一步:将虚拟机中/root目录下redis源码包中的redis.conf配置文件复制到虚拟机/usr/local/redis/bin/目录下 
      方式一:[root@itheima bin]# cp /root/redis-3.0.0/redis.conf /usr/local/redis/bin/ 
      方式二:[root@itheima bin]# cp /root/redis-3.0.0/redis.conf ./
  • 第二步:修改redis.conf,将daemonize由no改为yes 
      [root@itheima bin]# vim redis.conf
  • 第三步:执行命令,后端启动redis 
      [root@itheima bin]# ./redis-server redis.conf
  • 第四步:查看是否启动成功,通过查看进程号 
  • 关闭后端启动的方式: 
      强制关闭:[root@itheima bin]# kill -9 7272 
      正常关闭:[root@itheima bin]# ./redis-cli shutdown
  • 在项目中,建议使用正常关闭。 
    因为redis作为缓存来使用的话,是将数据存储到内存中, 
      如果使用正常关闭,则会将内存数据持久化到本地之后,再关闭。 
      如果使用强制关闭,则不会进行持久化操作,可能会造成部分数据的丢失。

3、Redis客户端的使用

3.1、redis自带的客户端(命令行)

  • 先启动服务端命令:[root@itheima bin]# ./redis-server redis.conf
  • 再启动客户端命令:[root@itheima bin]# ./redis-cli -h 127.0.0.1 -p 6379 
      -h:指定访问的redis服务器的ip地址 
      -p:指定访问的redis服务器的port端口
  • 如果不指定主机和端口也可以 
      即可以写成:[root@itheima bin]# ./redis-cli 
      使用默认配置:默认的ip【127.0.0.1】,默认的port【6379】
  • 关闭redis客户端的方式: 
      方式一:Ctrl+c 
      方式二:127.0.0.1:6379> quit
  • 进行数据测试: 
      127.0.0.1:6379> set s1 hello 
      OK 
      127.0.0.1:6379> get s1 
      “hello”

3.2、图形界面客户端(了解)

  • 安装文件位置: 
  • 安装之后,打开如下界面: 
  • 远程连接redis服务: 
  • 不能够连接上redis服务器,为什么呢? 
  • 原因:端口被拦截,需要关闭或者修改虚拟机的防火墙配置。(注意:实际开发中:只能修改防火墙配置,并不是关闭!) 
    CentOS7默认的防火墙不是iptables,而是firewalld。我们可以试一下systemctl stop firewalld关闭防火墙,但是不推荐该方式。 
    如果是iptables,就vim /etc/sysconfig/iptables修改配置即可。详细的过程,博主以后会整理补充上。 
    本博主的是CentOS7,防火墙使用的是firewalld,我们使用命令的方式来添加端口(修改后需要重启firewalld服务): 
      [root@itheima ~]# cd /etc/firewalld/zones/ 
      [root@itheima zones]# firewall-cmd –permanent –add-port=6379/tcp 
      [root@itheima zones]# service firewalld restart 
      Redirecting to /bin/systemctl restart firewalld.service 
      [root@itheima zones]#
  • 再次使用redis图形界面客户端连接redis服务器,连接成功,如下图所示: 
  • 注意:默认一共是16个数据库,每个数据库之间是相互隔离。数据库的数量是在redis.conf中配置的。 
  • 切换数据库使用命令:select 数据库编号,就可以选择指定的数据库来使用,索引从0开始,示例如下 
      127.0.0.1:6379> select 15 
      OK 
      127.0.0.1:6379[15]>

3.3、Java客户端Jedis(重点)

3.3.1、jedis介绍

  • Redis不仅是使用命令来操作,现在基本上主流的语言都有客户端支持,比如java、C、C#、C++、php、Node.js、Go等。
  • 在官方网站里罗列一些Java的客户端,有Jedis、Redisson、Jredis、JDBC-Redis、等其中官方推荐使用JedisRedisson。 在企业中用的最多的就是Jedis,下面我们就重点学习下Jedis。
  • Jedis同样也是托管在github上,地址:https://github.com/xetorthio/jedis

3.3.2、添加jar包

3.3.3、通过单实例连接redis服务器

创建一个普通的java项目,导入jar包 
测试代码如下:

  1. /**
  2. * 通过单实例连接redis服务器
  3. */
  4. @Test
  5. public void testJedisClient() {
  6. // 创建一个Jedis的连接
  7. Jedis jedis = new Jedis("192.168.5.128", 6379);
  8. // 选择数据库
  9. jedis.select(2);
  10. // 执行redis命令
  11. jedis.set("s4", "晓艺,你还好吗?");
  12. // 从redis中取值
  13. String result = jedis.get("s4");
  14. // 打印结果
  15. System.out.println(result);
  16. // 关闭连接
  17. jedis.close();
  18. }

3.3.4、通过连接池连接redis服务器

测试代码如下:

  1. /**
  2. * 通过连接池连接redis服务器
  3. */
  4. @Test
  5. public void testJedisPool() {
  6. // 创建一个连接池对象
  7. JedisPool jedisPool = new JedisPool("192.168.5.128", 6379);
  8. // 从连接池中获取jedis会话对象
  9. Jedis jedis = jedisPool.getResource();
  10. String result = jedis.get("s1");
  11. System.out.println(result);
  12. // 关闭连接
  13. jedis.close();
  14. // 关闭连接池
  15. jedisPool.close();
  16. }

3.3.5、spring整合JedisPool(自学)

添加spring的jar包 
配置spring配置文件applicationContext.xml 
applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  8. http://www.springframework.org/schema/mvc
  9. http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  10. http://www.springframework.org/schema/context
  11. http://www.springframework.org/schema/context/spring-context-3.2.xsd
  12. http://www.springframework.org/schema/aop
  13. http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
  14. http://www.springframework.org/schema/tx
  15. http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
  16. <!-- 连接池配置 -->
  17. <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
  18. <!-- 最大连接数 -->
  19. <property name="maxTotal" value="30" />
  20. <!-- 最大空闲连接数 -->
  21. <property name="maxIdle" value="10" />
  22. <!-- 每次释放连接的最大数目 -->
  23. <property name="numTestsPerEvictionRun" value="1024" />
  24. <!-- 释放连接的扫描间隔(毫秒) -->
  25. <property name="timeBetweenEvictionRunsMillis" value="30000" />
  26. <!-- 连接最小空闲时间 -->
  27. <property name="minEvictableIdleTimeMillis" value="1800000" />
  28. <!-- 连接空闲多久后释放, 当空闲时间>该值 且 空闲连接>最大空闲连接数 时直接释放 -->
  29. <property name="softMinEvictableIdleTimeMillis" value="10000" />
  30. <!-- 获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1 -->
  31. <property name="maxWaitMillis" value="1500" />
  32. <!-- 在获取连接的时候检查有效性, 默认false -->
  33. <property name="testOnBorrow" value="false" />
  34. <!-- 在空闲时检查有效性, 默认false -->
  35. <property name="testWhileIdle" value="true" />
  36. <!-- 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true -->
  37. <property name="blockWhenExhausted" value="false" />
  38. </bean>
  39. <!-- redis单机 通过连接池连接redis服务器 -->
  40. <bean id="jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="close">
  41. <constructor-arg name="poolConfig" ref="jedisPoolConfig" />
  42. <constructor-arg name="host" value="192.168.5.128" />
  43. <constructor-arg name="port" value="6379" />
  44. </bean>
  45. </beans>

测试代码如下:

  1. @Test
  2. public void testJedisPool() {
  3. JedisPool pool = (JedisPool) applicationContext.getBean("jedisPool");
  4. Jedis jedis = null;
  5. try {
  6. jedis = pool.getResource();
  7. jedis.set("s5", "lisi");
  8. String name = jedis.get("s5");
  9. System.out.println(name);
  10. } catch (Exception ex) {
  11. ex.printStackTrace();
  12. } finally {
  13. if (jedis != null) {
  14. // 关闭连接
  15. jedis.close();
  16. }
  17. }
  18. }

4、Redis的数据类型

Redis中存储数据是通过key-value存储的,对于value的类型有以下几种: 
  字符串 
  Hash类型 
  List 
  Set 
  SortedSet(zset) 
PS: 
  在redis中的命令语句中,命令是忽略大小写的,而key是不忽略大小写的

4.1、String类型

4.1.1、命令学习

  • (1)赋值
  1. 语法:
  2. SET key value
  3. 示例:
  4. 127.0.0.1:6379> set test 123
  5. OK
  • (2)取值
  1. 语法:
  2. GET key
  3. 示例:
  4. 127.0.0.1:6379> get test
  5. "123"

  • (3)设置+获取多个键值
  1. 语法:
  2. MSET key value [key value ...]
  3. MGET key [key ...]
  4. 示例:
  5. 127.0.0.1:6379> mset k1 v1 k2 v2 k3 v3
  6. OK
  7. 0.0.1:6379> get k1
  8. "v1"
  9. 127.0.0.1:6379> mget k1 k3
  10. 1) "v1"
  11. 2) "v3"
  • (4)取值并赋值
  1. 语法:
  2. GETSET key value
  3. 示例:
  4. 127.0.0.1:6379> get s2
  5. "111"
  6. 127.0.0.1:6379> getset s2 222
  7. "111"
  8. 127.0.0.1:6379> get s2
  9. "222"
  • (5)删除
  1. 语法:
  2. DEL key
  3. 示例:
  4. 127.0.0.1:6379> del test
  5. (integer) 1
  • (6)数值增减
  1. 递增数值:
  2. 当存储的字符串是整数时,Redis提供了一个实用的命令INCR,其作用是让当前键值递增,并返回递增后的值。
  3. 语法:
  4. INCR key
  5. 示例:
  6. 127.0.0.1:6379> incr num
  7. (integer) 1
  8. 127.0.0.1:6379> incr num
  9. (integer) 2
  10. 127.0.0.1:6379> incr num
  11. (integer) 3
  12. --------------------------------
  13. 增加指定的整数:
  14. 每次增加固定的整数。
  15. 语法:
  16. INCRBY key increment
  17. 示例:
  18. 127.0.0.1:6379> incrby num 2
  19. (integer) 5
  20. 127.0.0.1:6379> incrby num 2
  21. (integer) 7
  22. 127.0.0.1:6379> incrby num 2
  23. (integer) 9
  24. --------------------------------
  25. 递减数值:
  26. 语法:
  27. DECR key
  28. 示例:
  29. 127.0.0.1:6379> decr num
  30. (integer) 9
  31. 127.0.0.1:6379> decr num
  32. (integer) 8
  33. --------------------------------
  34. 减少指定的整数:
  35. 语法:
  36. DECRBY key decrement
  37. 示例:
  38. 127.0.0.1:6379> decr num
  39. (integer) 6
  40. 127.0.0.1:6379> decr num
  41. (integer) 5
  42. 127.0.0.1:6379> decrby num 3
  43. (integer) 2
  44. 127.0.0.1:6379> decrby num 3
  45. (integer) -1
  • (7)其它命令(自学)
  1. 向尾部追加值:
  2. APPEND的作用是向键值的末尾追加value。如果键不存在则将该键的值设置为value,即相当于 SET key value。返回值是追加后字符串的总长度。
  3. 语法:
  4. APPEND key value
  5. 示例:
  6. 127.0.0.1:6379> set str hello
  7. OK
  8. 127.0.0.1:6379> append str " world!"
  9. (integer) 12
  10. 127.0.0.1:6379> get str
  11. "hello world!"
  12. --------------------------------
  13. 获取字符串长度:
  14. STRLEN命令返回键值的长度,如果键不存在则返回0
  15. 语法:
  16. STRLEN key
  17. 示例:
  18. 127.0.0.1:6379> strlen str
  19. (integer) 0
  20. 127.0.0.1:6379> set str hello
  21. OK
  22. 127.0.0.1:6379> strlen str
  23. (integer) 5

4.1.2、应用

  • (1)自增主键
  1. 商品编号、订单号采用string的递增数字特性生成。
  2. 定义商品编号keyitems:id
  3. 示例:
  4. 192.168.101.3:7003> INCR items:id
  5. (integer) 2
  6. 192.168.101.3:7003> INCR items:id
  7. (integer) 3

4.2、Hash类型

  • 散列类型(Map类型)

4.2.1、使用string的问题

  假设有User对象以JSON序列化的形式存储到Redis中,User对象有id、username、password、age、name等属性,存储的过程如下: 
  保存、更新: 
  User对象 –> json(string) –> redis 
  如果在业务上只是更新age属性,其他的属性并不做更新我应该怎么做呢? 
  如果仍然采用上边的方法在传输、处理时会造成资源浪费,下边讲的hash可以很好的解决这个问题。hash类型可以将粒度控制的很精细。

4.2.2、redis hash介绍

hash叫散列类型,它提供了字段和字段值的映射。字段值只能是字符串类型,不支持散列类型、集合类型等其它类型。如下:

4.2.3、命令学习

  • (1)赋值
  1. HSET命令不区分插入和更新操作,当执行插入操作时HSET命令返回1,当执行更新操作时返回0
  2. --------------------------------
  3. 一次只能设置一个字段值。
  4. 语法:
  5. HSET key field value
  6. 示例:
  7. 127.0.0.1:6379> hset user username zhangsan
  8. (integer) 1
  9. --------------------------------
  10. 一次可以设置多个字段值。
  11. 语法:
  12. HMSET key field value [field value ...]
  13. 示例:
  14. 127.0.0.1:6379> hmset user age 20 username lisi
  15. OK
  16. --------------------------------
  17. 当字段不存在时赋值,类似HSET,区别在于如果字段存在,该命令不执行任何操作。
  18. 语法:
  19. HSETNX key field value
  20. 示例:
  21. 127.0.0.1:6379> hsetnx user age 30 如果user中没有age字段则设置age值为30,否则不做任何操作
  22. (integer) 0
  • (2)取值
  1. 一次只能获取一个字段值。
  2. 语法:
  3. HGET key field
  4. 示例:
  5. 127.0.0.1:6379> hget user username
  6. "zhangsan"
  7. --------------------------------
  8. 一次可以获取多个字段值。
  9. 语法:
  10. HMGET key field [field ...]
  11. 示例:
  12. 127.0.0.1:6379> hmget user age username
  13. 1) "20"
  14. 2) "lisi"
  15. --------------------------------
  16. 获取所有字段值。
  17. 语法:
  18. HGETALL key
  19. 示例:
  20. 127.0.0.1:6379> hgetall user
  21. 1) "age"
  22. 2) "20"
  23. 3) "username"
  24. 4) "lisi"
  • (3)删除
  1. 可以删除一个或多个字段,返回值是被删除的字段个数。
  2. 语法:
  3. HDEL key field [field ...]
  4. 示例:
  5. 127.0.0.1:6379> hdel user age
  6. (integer) 1
  7. 127.0.0.1:6379> hdel user age name
  8. (integer) 0
  9. 127.0.0.1:6379> hdel user age username
  10. (integer) 1
  • (4)增加数值
  1. 语法:
  2. HINCRBY key field increment
  3. 示例:
  4. 127.0.0.1:6379> hincrby user age 2 将用户的年龄加2
  5. (integer) 22
  6. 127.0.0.1:6379> hget user age 获取用户的年龄
  7. "22"
  • (5)其它命令(自学)
  1. 判断字段是否存在。存在返回1,不存在返回0
  2. 语法:
  3. HEXISTS key field
  4. 示例:
  5. 127.0.0.1:6379> hexists user age 查看user中是否有age字段
  6. (integer) 1
  7. 127.0.0.1:6379> hexists user name 查看user中是否有name字段
  8. (integer) 0
  9. --------------------------------
  10. 只获取字段名或只获取字段值。
  11. 语法:
  12. HKEYS key
  13. HVALS key
  14. 示例:
  15. 127.0.0.1:6379> hmset user age 20 name lisi
  16. OK
  17. 127.0.0.1:6379> hkeys user
  18. 1) "age"
  19. 2) "name"
  20. 127.0.0.1:6379> hvals user
  21. 1) "20"
  22. 2) "lisi"
  23. --------------------------------
  24. 获取字段的数量。
  25. 语法:
  26. HLEN key
  27. 示例:
  28. 127.0.0.1:6379> hlen user
  29. (integer) 2

4.2.4、应用

  • (1)存储商品信息
  1. 商品字段
  2. 【商品id、商品名称、商品描述、商品库存、商品好评】
  3. 定义商品信息的key
  4. 商品1001的信息在Redis中的key为:[items:1001]
  5. 存储商品信息
  6. 192.168.101.3:7003> HMSET items:1001 id 3 name apple price 999.9
  7. OK
  8. 获取商品信息
  9. 192.168.101.3:7003> HGET items:1001 id
  10. "3"
  11. 192.168.101.3:7003> HGETALL items:1001
  12. 1) "id"
  13. 2) "3"
  14. 3) "name"
  15. 4) "apple"
  16. 5) "price"
  17. 6) "999.9"

4.3、List类型(列表类型)

4.3.1、ArrayList与LinkedList的区别

  ArrayList使用数组方式存储数据,所以根据索引查询数据速度快,而新增或者删除元素时需要设计到位移操作,所以比较慢。 
  LinkedList使用双向链表方式存储数据,每个元素都记录前后元素的指针,所以插入、删除数据时只是更改前后元素的指针指向即可,速度非常快。然后通过下标查询元素时需要从头开始索引,所以比较慢,但是如果查询前几个元素或后几个元素速度比较快。

双向链表添加节点示意图: 
 
双向链表删除节点示意图: 

4.3.2、redis list介绍

  列表类型(list)可以存储一个有序的字符串列表,常用的操作是向列表两端添加元素,或者获得列表的某一个片段。 
  列表类型内部是使用双向链表(double linked list)实现的,所以向列表两端添加元素的时间复杂度为0(1),获取越接近两端的元素速度就越快。这意味着即使是一个有几千万个元素的列表,获取头部或尾部的10条记录也是极快的。

4.3.3、命令学习

  • (1)向列表两端增加元素
  1. 向列表左边增加元素。
  2. 语法:
  3. LPUSH key value [value ...]
  4. 示例:
  5. 127.0.0.1:6379> lpush list:1 1 2 3
  6. (integer) 3
  7. --------------------------------
  8. 向列表右边增加元素
  9. 语法:
  10. RPUSH key value [value ...]
  11. 示例:
  12. 127.0.0.1:6379> rpush list:1 4 5 6
  13. (integer) 6

存储过程如下图: 

  • (2)查看列表
  1. LRANGE命令是列表类型最常用的命令之一,获取列表中的某一片段,将返回startstop之间的所有元素(包含两端的元素),索引从0开始。索引可以是负数,如:“-1”代表最后边的一个元素。
  2. 语法:
  3. LRANGE key start stop
  4. 示例:
  5. 127.0.0.1:6379> lrange list:1 0 2
  6. 1) "3"
  7. 2) "2"
  8. 3) "1"
  9. 127.0.0.1:6379> lrange list:1 0 -1
  10. 1) "3"
  11. 2) "2"
  12. 3) "1"
  13. 4) "4"
  14. 5) "5"
  15. 6) "6"
  16. 127.0.0.1:6379>
  • (3)从列表两端弹出元素
  1. LPOP命令从列表左边弹出一个元素,会分两步完成:
  2. 第一步是将列表左边的元素从列表中移除
  3. 第二步是返回被移除的元素值。
  4. 语法:
  5. LPOP key
  6. RPOP key
  7. 示例:
  8. 127.0.0.1:6379> lpop list:1
  9. "3"
  10. 127.0.0.1:6379> rpop list:1
  11. "6"
  12. 127.0.0.1:6379> lrange list:1 0 -1
  13. 1) "2"
  14. 2) "1"
  15. 3) "4"
  16. 4) "5"
  • (4)获取列表中元素的个数
  1. 语法:
  2. LLEN key
  3. 示例:
  4. 127.0.0.1:6379> llen list:1
  5. (integer) 4
  • (5)其它命令(自学)
  1. 删除列表中指定的值
  2. LREM命令会删除列表中前count个值为value的元素,返回实际删除的元素个数。根据count值的不同,该命令的执行方式会有所不同:
  3. count>0时, LREM会从列表左边开始删除。
  4. count<0时, LREM会从列表后边开始删除。
  5. count=0时, LREM删除所有值为value的元素。
  6. 语法:
  7. LREM key count value
  8. --------------------------------
  9. 获得指定索引的元素值
  10. 语法:
  11. LINDEX key index
  12. 示例:
  13. 127.0.0.1:6379> lrange list:1 0 -1
  14. 1) "2"
  15. 2) "1"
  16. 3) "4"
  17. 4) "5"
  18. 127.0.0.1:6379> lindex list:1 2
  19. "4"
  20. 127.0.0.1:6379>
  21. --------------------------------
  22. 设置指定索引的元素值
  23. 语法:
  24. LSET key index value
  25. 示例:
  26. 127.0.0.1:6379> lrange list:1 0 -1
  27. 1) "2"
  28. 2) "1"
  29. 3) "4"
  30. 4) "5"
  31. 127.0.0.1:6379> lset list:1 2 2
  32. OK
  33. 127.0.0.1:6379> lrange l:list 0 -1
  34. 1) "2"
  35. 2) "1"
  36. 3) "2"
  37. 4) "5"
  38. --------------------------------
  39. 只保留列表指定片段
  40. 指定范围和LRANGE一致。
  41. 语法:
  42. LTRIM key start stop
  43. 示例:
  44. 127.0.0.1:6379> lrange list:1 0 -1
  45. 1) "2"
  46. 2) "1"
  47. 3) "2"
  48. 4) "5"
  49. 127.0.0.1:6379> ltrim list:1 0 2
  50. OK
  51. 127.0.0.1:6379> lrange list:1 0 -1
  52. 1) "2"
  53. 2) "1"
  54. 3) "2"
  55. 127.0.0.1:6379>
  56. --------------------------------
  57. 向列表中插入元素
  58. 该命令首先会在列表中从左到右查找值为pivot的元素,然后根据第二个参数是BEFORE还是AFTER来决定将value插入到该元素的前面还是后面。
  59. 语法:
  60. LINSERT key BEFORE|AFTER pivot value
  61. 示例:
  62. 127.0.0.1:6379> lrange list:1 0 -1
  63. 1) "2"
  64. 2) "1"
  65. 3) "2"
  66. 127.0.0.1:6379> linsert list:1 after 1 4
  67. (integer) 4
  68. 127.0.0.1:6379> lrange list:1 0 -1
  69. 1) "2"
  70. 2) "1"
  71. 3) "4"
  72. 4) "2"
  73. 127.0.0.1:6379>
  74. --------------------------------
  75. 将元素从一个列表转移到另一个列表中
  76. 语法:
  77. RPOPLPUSH source destination
  78. 示例:
  79. 127.0.0.1:6379> rpoplpush list:1 newlist
  80. "2"
  81. 127.0.0.1:6379> lrange newlist 0 -1
  82. 1) "2"
  83. 127.0.0.1:6379> lrange list:1 0 -1
  84. 1) "2"
  85. 2) "1"
  86. 3) "4"

4.3.4、应用

  • (1)商品评论列表
  1. 思路:
  2. Redis中创建商品评论列表。
  3. 用户发布商品评论,将评论信息转成json存储到list中。
  4. 用户在页面查询评论列表,从redis中取出json数据展示到页面。
  5. 定义商品评论列表key
  6. 商品编号为1001的商品评论keyitems:comment:1001
  7. 192.168.5.128:7001> LPUSH items:comment:1001 '{"id":1,"name":"商品不错,很好!","date":1430295077289}'

4.4、Set类型(集合类型)

4.4.1、redis set介绍

  集合中的数据是不重复且没有顺序。 
  集合类型的常用操作是向集合中加入或删除元素、判断某个元素是否存在等,由于集合类型的Redis内部是使用值为空的散列表实现,所有这些操作的时间复杂度都为0(1)。 
  Redis还提供了多个集合之间的交集、并集、差集的运算。 
  集合类型和列表类型的对比: 
    集合类型:无序、不可重复 
    列表类型:有序、可重复

4.4.2、命令学习

  • (1)增加/删除元素
  1. 语法:
  2. SADD key member [member ...]
  3. 示例:
  4. 127.0.0.1:6379> sadd set a b c
  5. (integer) 3
  6. 127.0.0.1:6379> sadd set a
  7. (integer) 0
  8. 语法:
  9. SREM key member [member ...]
  10. 示例:
  11. 127.0.0.1:6379> srem set c d
  12. (integer) 1
  • (2)获得集合中的所有元素
  1. 语法:
  2. SMEMBERS key
  3. 示例:
  4. 127.0.0.1:6379> smembers set
  5. 1) "b"
  6. 2) "a"
  • (3)判断元素是否在集合中
  1. 语法:
  2. SISMEMBER key member
  3. 示例:
  4. 127.0.0.1:6379> sismember set a
  5. (integer) 1
  6. 127.0.0.1:6379> sismember set h
  7. (integer) 0

4.4.3、运算命令学习

  • (1)集合的差集运算 A - B 
     
    属于A并且不属于B的元素构成的集合。
  1. 语法:
  2. SDIFF key [key ...]
  3. 示例:
  4. 127.0.0.1:6379> sadd set1 1 2 3
  5. (integer) 3
  6. 127.0.0.1:6379> sadd set2 2 3 4 5
  7. (integer) 4
  8. 127.0.0.1:6379> sdiff set1 set2
  9. 1) "1"
  10. 127.0.0.1:6379> sdiff set2 set1
  11. 1) "4"
  12. 2) "5"
  • (2)集合的交集运算 A ∩ B 
     
    属于A或者属于B的元素构成的集合。
  1. 语法:
  2. SINTER key [key ...]
  3. 示例:
  4. 127.0.0.1:6379> sinter set1 set2
  5. 1) "2"
  6. 2) "3"
  • (3)集合的并集运算 A ∪ B 
     
    属于A或者属于B的元素构成的集合。
  1. 语法:
  2. SUNION key [key ...]
  3. 示例:
  4. 127.0.0.1:6379> sunion setA setB
  5. 1) "1"
  6. 2) "2"
  7. 3) "3"
  8. 4) "4"
  9. 5) "5"

4.4.4、其它命令(自学)

  1. 获得集合中元素的个数
  2. 语法:
  3. SCARD key
  4. 示例:
  5. 127.0.0.1:6379> smembers setA
  6. 1) "1"
  7. 2) "2"
  8. 3) "3"
  9. 127.0.0.1:6379> scard setA
  10. (integer) 3
  11. --------------------------------
  12. 从集合中弹出一个元素
  13. 注意:由于集合是无序的,所有SPOP命令会从集合中随机选择一个元素弹出。
  14. 语法:
  15. SPOP key
  16. 示例:
  17. 127.0.0.1:6379> spop setA
  18. "1"

4.5、SortedSet类型(zset类型)

4.5.1、redis sorted set介绍

  在集合类型的基础上,有序集合类型为集合中的每个元素都关联一个分数,这使得我们不仅可以完成插入、删除和判断元素是否存在在集合中,还能够获得分数最高或最低的前N个元素、获取指定分数范围内的元素等与分数有关的操作。 
  Sortedset是有序集合,可排序的,但是唯一。 
  在某些方面有序集合列表类型有些相似。 
    1、二者都是有序的。 
    2、二者都可以获得某一范围的元素。 
  但是,二者有着很大区别: 
    1、列表类型是通过链表实现的,获取靠近两端的数据速度极快,而当元素增多后,访问中间数据的速度会变慢。 
    2、有序集合类型使用散列表实现,所有即使读取位于中间部分的数据也很快。 
    3、列表中不能简单的调整某个元素的位置,但是有序集合可以(通过更改分数实现)。 
    4、有序集合要比列表类型更耗内存

4.5.2、命令学习

  • (1)增加元素
  1. 向有序集合中加入一个元素和该元素的分数,如果该元素已经存在则会用新的分数替换原有的分数。返回值是新加入到集合中的元素个数,不包含之前已经存在的元素。
  2. 语法:
  3. ZADD key score member [score member ...]
  4. 示例:
  5. 127.0.0.1:6379> zadd zset1 80 zhangsan 89 lisi 94 wangwu
  6. (integer) 3
  7. 127.0.0.1:6379> zadd zset1 97 lisi
  8. (integer) 0
  • (2)获取元素的分数
  1. 语法:
  2. ZSCORE key member
  3. 示例:
  4. 127.0.0.1:6379> zscore zset1 lisi
  5. "97"
  • (3)删除元素
  1. 移除有序集key中的一个或多个成员,不存在的成员将被忽略。
  2. key存在但不是有序集类型时,返回一个错误。
  3. 语法:
  4. ZREM key member [member ...]
  5. 示例“
  6. 127.0.0.1:6379> zrem zset1 lisi
  7. (integer) 1
  • (4)获得排名在某个范围的元素列表(从小到大)
  1. 获得排名在某个范围的元素列表 (从小到大)
  2. 按照元素分数从小到大的顺序返回索引从startstop之间的所有元素(包含两端的元素)
  3. 语法:
  4. ZRANGE key start stop [WITHSCORES]
  5. 示例:
  6. 127.0.0.1:6379> zrange zset1 0 2
  7. 1) "zhangsan"
  8. 2) "wangwu"
  9. 3) "lisi"
  10. --------------------------------
  11. 按照元素分数从大到小的顺序返回索引从startstop之间的所有元素(包含两端的元素)
  12. 语法:
  13. ZREVRANGE key start stop [WITHSCORES]
  14. 示例:
  15. 127.0.0.1:6379> zrevrange zset1 0 2
  16. 1) "lisi"
  17. 2) "wangwu"
  18. 3) "zhangsan"
  19. --------------------------------
  20. 如果需要获得元素的分数的可以在命令尾部加上WITHSCORES参数
  21. 示例:
  22. 127.0.0.1:6379> zrange zset1 0 1 WITHSCORES
  23. 1) "zhangsan"
  24. 2) "80"
  25. 3) "wangwu"
  26. 4) "94"
  • (5)其它命令(自学)
  1. 获得指定分数范围的元素
  2. 语法:
  3. ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]
  4. 示例:
  5. 127.0.0.1:6379> ZRANGEBYSCORE zset1 90 97 WITHSCORES
  6. 1) "wangwu"
  7. 2) "94"
  8. 3) "lisi"
  9. 4) "97"
  10. 127.0.0.1:6379> ZRANGEBYSCORE zset1 70 100 limit 1 2
  11. 1) "wangwu"
  12. 2) "lisi"
  13. --------------------------------
  14. 增加某个元素的分数
  15. 返回值是更改后的分数
  16. 语法:
  17. ZINCRBY key increment member
  18. 示例:
  19. 127.0.0.1:6379> ZINCRBY zset1 4 lisi
  20. "101"
  21. --------------------------------
  22. 获得集合中元素的数量
  23. 语法:
  24. ZCARD key
  25. 示例:
  26. 127.0.0.1:6379> ZCARD zset1
  27. (integer) 3
  28. --------------------------------
  29. 获得指定分数范围内的元素个数
  30. 语法:
  31. ZCOUNT key min max
  32. 示例:
  33. 127.0.0.1:6379> ZCOUNT zset1 80 90
  34. (integer) 1
  35. --------------------------------
  36. 按照排名范围删除元素
  37. 语法:
  38. ZREMRANGEBYRANK key start stop
  39. 示例:
  40. 127.0.0.1:6379> ZREMRANGEBYRANK zset1 0 1
  41. (integer) 2
  42. 127.0.0.1:6379> ZRANGE scoreboard 0 -1
  43. 1) "lisi"
  44. --------------------------------
  45. 按照分数范围删除元素
  46. 语法:
  47. ZREMRANGEBYSCORE key min max
  48. 示例:
  49. 127.0.0.1:6379> zadd zset1 84 zhangsan
  50. (integer) 1
  51. 127.0.0.1:6379> ZREMRANGEBYSCORE zset1 80 100
  52. (integer) 1
  53. --------------------------------
  54. 获取元素的排名
  55. 从小到大
  56. 语法:
  57. ZRANK key member
  58. 示例:
  59. 127.0.0.1:6379> ZRANK zset1 lisi
  60. (integer) 0
  61. 从大到小
  62. 语法:
  63. ZREVRANK key member
  64. 示例:
  65. 127.0.0.1:6379> ZREVRANK zset1 zhangsan
  66. (integer) 1

4.5.3、应用

  • (1)商品销售排行榜
  1. 需求:
  2. 根据商品销售量对商品进行排行显示。
  3. 思路:
  4. 定义商品销售排行榜(sorted set集合),Keyitems:sellsort,分数为商品销售量。
  5. 写入商品销售量:
  6. 商品编号1001的销量是9,商品编号1002的销量是10
  7. 192.168.101.3:7007> ZADD items:sellsort 9 1001 10 1002
  8. 商品编号1001的销量加1
  9. 192.168.101.3:7001> ZINCRBY items:sellsort 1 1001
  10. 商品销量前10名:
  11. 192.168.101.3:7001> ZRANGE items:sellsort 0 9 withscores

5、keys命令(了解)

5.1、常用命令(自学)

  • (1)keys
  1. 返回满足给定pattern的所有key
  2. 示例:
  3. 127.0.0.1:6379> keys *
  4. 1) "zset1"
  5. 2) "list:1"
  6. 3) "s1"
  7. 4) "s2"
  8. 5) "newlist"
  9. 6) "s3"
  10. 7) "set2"
  11. 8) "set1"
  • (2)exists
  1. 确认一个key是否存在
  2. 从示例结果来看,数据库中不存在HongWan这个key,但是age这个key是存在的
  3. 示例:
  4. 127.0.0.1:6379> exists set8
  5. (integer) 0
  6. 127.0.0.1:6379> exists set1
  7. (integer) 1
  • (3)del
  1. 删除一个key
  2. 示例:
  3. 127.0.0.1:6379> del s3
  4. (integer) 1
  5. 127.0.0.1:6379> exists set3
  6. (integer) 0
  7. 127.0.0.1:6379>
  • (4)rename
  1. 重命名key
  2. 从示例结果来看,s1成功的被我们改名为s1_new了。
  3. 示例:
  4. 127.0.0.1:6379> keys *
  5. 1) "zset1"
  6. 2) "list:1"
  7. 3) "s1"
  8. 4) "s2"
  9. 5) "newlist"
  10. 6) "set2"
  11. 7) "set1"
  12. 127.0.0.1:6379> rename s1 s1_new
  13. OK
  14. 127.0.0.1:6379> keys *
  15. 1) "zset1"
  16. 2) "list:1"
  17. 3) "s2"
  18. 4) "newlist"
  19. 5) "set2"
  20. 6) "s1_new"
  21. 7) "set1"
  • (5)type
  1. 返回值的类型
  2. 从示例结果来看,这个方法可以非常简单的判断出值的类型。
  3. 示例:
  4. 127.0.0.1:6379> keys *
  5. 1) "zset1"
  6. 2) "list:1"
  7. 3) "s2"
  8. 4) "newlist"
  9. 5) "set2"
  10. 6) "s1_new"
  11. 7) "set1"
  12. 127.0.0.1:6379> type s2
  13. string
  14. 127.0.0.1:6379> type set1
  15. set
  16. 127.0.0.1:6379> type zset1
  17. zset
  18. 127.0.0.1:6379> type list:1
  19. list

5.2、设置key的生存时间

  • Redis在实际使用过程中更多的用作缓存,然而缓存的数据一般都是需要设置生存时间的,即:到期后数据销毁。
  1. EXPIRE key seconds 设置key的生存时间(单位:秒)key在多少秒后会自动删除
  2. TTL key 查看key生于的生存时间
  3. PERSIST key 清除生存时间
  4. PEXPIRE key milliseconds 生存时间设置单位为:毫秒
  5. 示例:
  6. 127.0.0.1:6379> keys *
  7. 1) "zset1"
  8. 2) "list:1"
  9. 3) "s2"
  10. 4) "newlist"
  11. 5) "set2"
  12. 6) "s1_new"
  13. 7) "set1"
  14. 127.0.0.1:6379> expire s2 10 设置s2的生存时间为10
  15. (integer) 1
  16. 127.0.0.1:6379> ttl s2 查看s2的生于生成时间还有4秒删除
  17. (integer) 4
  18. 127.0.0.1:6379> ttl s2
  19. (integer) -2
  20. 127.0.0.1:6379> get s2 获取s2的值,已经删除
  21. (nil)

6、Redis的持久化方案

6.1、RDB持久化(默认)

  RDB方式的持久化是通过快照(snapshotting)完成的,当符合一定条件时Redis会自动将内存中的数据进行快照并持久化到硬盘。 
  RDB是Redis默认采用的持久化方式。

6.1.1、设置持久化快照的条件

在redis.conf中修改持久化快照的条件,如下图: 
 
详解如下:

  1. save 开头的一行就是持久化配置,可以配置多个条件(每行配置一个条件),每个条件之间是“或”的关系。
  2. save 900 1 表示15分钟(900秒)内至少1个键被更改则进行快照。
  3. save 300 10 表示5分钟(300秒)内至少10个键被更改则进行快照。
  4. save 60 10000 表示1分钟(60秒)内至少10000个键被更改则进行快照。

6.1.2、设置快照文件(持久化文件)存储的名称和目录

在redis.conf中可以指定持久化文件存储的目录,如下图: 
 
详解如下:

  1. dbfilename dump.rdb 表示设置而快照文件(持久化文件)存储的名称为:dump.rdb
  2. dir ./ 表示设置而快照文件(持久化文件)存储的目录为:在当前目录下
  3. Redis启动后会读取RDB快照文件,将数据从硬盘载入到内存。根据数据量大小与结构和服务器性能不同,这个时间也不同。
  4. 通常将记录一千万个字符串类型键、大小为1GB的快照文件载入到内存中需要花费2030秒钟。

6.1.4、RDB问题总结

  通过RDB方式实现持久化,一旦Redis异常退出(非法关闭),就会丢失最后一次快照以后更改的所有数据。这就需要开发者根据具体的应用场合,通过组合设置自动快照条件的方式来将可能发生的数据损失控制在能够接受的范围。 
  如果数据很重要以至于无法承受任何损失,则可以考虑使用AOF方式进行持久化。 
  即:一旦redis非法关闭,那么会丢失最后一次持久化之后的数据。 
  如果数据不重要,则不必要关心。 
  如果数据不能允许丢失,那么要使用AOF方式。

6.2、AOF持久化

详解如下:

  1. 默认情况下Redis没有开启AOFappend only file)方式的持久化。
  2. 可以通过修改redis.conf配置文件中的appendonly参数开启,如下:
  3. appendonly yes
  4. 开启AOF持久化后每执行一条会更改Redis中的数据的命令,Redis就会将该命令写入硬盘中的AOF文件。
  5. AOF文件的保存位置和RDB文件的位置相同,都是通过dir参数设置的。
  6. dir ./
  7. 默认的文件名是appendonly.aof,可以通过appendfilename参数修改:
  8. appendfilename appendonly.aof
  9. 在同时使用aofrdb方式时,如果redis重启,则数据从aof文件加载。

7、Redis的主从复制

7.1、什么是主从复制

  • 持久化保证了即使redis服务重启也不会丢失数据,因为redis服务重启后会将硬盘上持久化的数据恢复到内存中,但是当redis服务器的硬盘损坏了可能会导致数据丢失,如果通过redis的主从复制机制就可以避免这种单点故障,如下图所示: 
  • 详解如下: 
    • 主redis中的数据有两个副本(replication)即从redis1和从redis2,即使一台redis服务器宕机其它两台redis服务也可以继续提供服务。
    • 主redis中的数据和从redis上的数据保持实时同步,当主redis写入数据时通过主从复制机制会复制到两个从redis服务上。
    • 只有一个主redis,可以有多个从redis。
    • 主从复制不会阻塞master,在同步数据时,master可以继续处理client请求。
    • 一个redis可以即是主又是从,如下图: 

7.2、主从配置

7.2.1、主redis配置

  • 无需特殊配置。

7.2.2、从redis配置

  • 由于目前我们只有一台电脑,需要模拟出两台服务器。
  • 第一步:复制出一个从机bin2/ 
      [root@itheima redis]# cp bin/ bin2 –r
  • 第二步:修改【从redis服务器】上的redis.conf文件 
     
      上边的配置说明当前该【从redis服务器】所对应的【主redis服务器】的IP是192.168.5.128,端口是6379。
  • 第三步:修改【从redis服务器】上的redis.conf文件,修改port地址为6380 
  • 第四步:清除【从redis服务器】中的持久化文件为了保证主从机数据一致 
      [root@itheima bin2]# rm -rf appendonly.aof dump.rdb
  • 第五步:启动【从redis服务器】 
      [root@itheima bin2]# ./redis-server redis.conf
  • 第六步:启动【6380的客户端】 
      [root@itheima bin2]# ./redis-cli -p 6380
  • 注意: 
      主机一旦发生增删改操作,那么从机会将数据同步到从机中。 
      从机不能执行写操作(增删改操作)。

8、Redis的集群(重点)

8.1、redis-cluster架构图

 
详解如下:

  1. 架构细节:
  2. (1) 所有的redis节点彼此互联(`PING-PONG机制`),内部使用`二进制协议`优化传输速度和带宽。
  3. (2) 节点的fail(失败)是通过集群中`超过半数的节点检测失效`时才生效。即`集群搭建中主机的个数为奇数`
  4. (3) 客户端与redis节点直连,不需要中间proxy层,客户端不需要连接集群所有节点,连接集群中任何一个可用节点即可。
  5. (4) redis-cluster把所有的物理节点映射到[0-16383]slot(槽)上,cluster负责维护node<-->slot<-->value
  6. Redis 集群中内置了 `16384 个哈希槽`,当需要在 Redis 集群中放置一个 key-value 时,redis 先对 key 使用 crc16 算法算出一个结果,然后把结果`对 16384 求余数`,这样每个 key 都会对应一个编号在 0-16383 之间的哈希槽,redis 会根据节点数量`大致均等`的将哈希槽映射到不同的节点。

示例如下: 

8.2、redis-cluster投票:容错

 
详解如下:

  1. (1) 集群中所有master参与投票,如果半数以上master节点与其中一个master节点通信超过(cluster-node-timeout),认为该master节点挂掉。
  2. (2) 什么时候整个集群不可用(cluster_state:fail)?
  3. 1、如果集群任意master挂掉,且当前master没有slave,则集群进入fail状态。也可以理解成集群的[0-16383]slot映射不完全时进入fail状态。
  4. 2、如果集群超过半数以上master挂掉,无论是否有slave,集群进入fail状态。

8.3、搭建ruby环境

  • redis集群管理工具redis-trib.rb依赖ruby环境,首先需要安装ruby环境。
  • 第一步:安装ruby环境 
      [root@itheima bin]# yum install ruby 
      [root@itheima bin]# yum install rubygems
  • 第二步:使用sftp工具将以下文件上传到linux系统 
      sftp> put -r “E:\学习资料\java\java就业班\17、第十七阶段redis(1天)\redis\res\ruby和redis接口\redis-3.0.0.gem”
  • 第三步:安装ruby和redis接口 
      [root@itheima ~]# gem install redis-3.0.0.gem
  • 第四步:将redis-3.0.0包下src目录中的redis集群搭建脚本文件redis-trib.rb拷贝到/user/local/redis/redis-cluster 目录下(注意:先在/user/local/redis/目录下创建目录redis-cluster) 
      [root@itheima ~]# cd /root/redis-3.0.0/src/ 
      [root@itheima src]# ll *rb 
      -rwxr-xr-x. 1 root root 48141 11月 3 19:30 redis-trib.rb 
      [root@itheima src]# cp redis-trib.rb /usr/local/redis/redis-cluster
  • 第五步:查看是否拷贝成功 
      [root@itheima redis-cluster]# ll 
      总用量 48 
      -rwxr-xr-x. 1 root root 48141 11月 3 19:30 redis-trib.rb

8.4、搭建redis集群

  • 搭建集群最少也得需要3台主机,如果每台主机再配置一台从机的话,则最少需要6台机器。
  • 现在我们需要在一台电脑上模拟出6台电脑。 
    • 端口设计如下:7001-7006
  • 第一步:复制出一个7001机器 
      [root@itheima redis]# cp bin ./redis-cluster/7001 -r
  • 第二步:如果存在持久化文件,则删除 
      [root@itheima 7001]# rm -rf appendonly.aof dump.rdb
  • 第三步:设置集群参数,修改redis.conf配置文件,打开cluster-enable yes 
  • 第四步:修改端口 
  • 第五步:复制出7002-7006机器 
      [root@itheima redis-cluster]# cp 7001/ 7002 -r 
      [root@itheima redis-cluster]# cp 7001/ 7003 -r 
      [root@itheima redis-cluster]# cp 7001/ 7004 -r 
      [root@itheima redis-cluster]# cp 7001/ 7005 -r 
      [root@itheima redis-cluster]# cp 7001/ 7006 -r
  • 第六步:依次修改7002-7006机器的端口
  • 第七步:启动7001-7006这六台机器,我们自己写一个脚本文件start-all.sh批量启动它们: 
      [root@itheima redis-cluster]# vim start-all.sh 
     
    补上1:我们自己写一个脚本文件shutdown-all.sh批量关闭它们: 
      [root@itheima redis-cluster]# vim shutdown-all.sh 
     
    补上2:我们自己写一个脚本文件delete-aof-rdb-nodes.sh批量删除持久化文件和节点配置文件: 
      [root@itheima redis-cluster]# vim delete-aof-rdb-nodes.sh 
     
    注意:自定义的脚本文件需要授予写权限,方可使用!!!
  • 第八步:修改start-all.sh文件的权限 
      [root@itheima redis-cluster]# chmod u+x start-all.sh
  • 第九步:执行脚本文件start-all.sh,批量启动它们 
      [root@itheima redis-cluster]# ./start-all.sh
  • 第十步:查看启动状态 
      [root@itheima redis-cluster]# ps -aux | grep redis 
  • 第十一步:创建集群
  1. [root@itheima redis-cluster]# ./redis-trib.rb create --replicas 1 192.168.5.128:7001 192.168.5.128:7002 192.168.5.128:7003 192.168.5.128:7004 192.168.5.128:7005 192.168.5.128:7006
  2. >>> Creating cluster
  3. Connecting to node 192.168.5.128:7001: OK
  4. Connecting to node 192.168.5.128:7002: OK
  5. Connecting to node 192.168.5.128:7003: OK
  6. Connecting to node 192.168.5.128:7004: OK
  7. Connecting to node 192.168.5.128:7005: OK
  8. Connecting to node 192.168.5.128:7006: OK
  9. >>> Performing hash slots allocation on 6 nodes...
  10. Using 3 masters:
  11. 192.168.5.128:7001
  12. 192.168.5.128:7002
  13. 192.168.5.128:7003
  14. Adding replica 192.168.5.128:7004 to 192.168.5.128:7001
  15. Adding replica 192.168.5.128:7005 to 192.168.5.128:7002
  16. Adding replica 192.168.5.128:7006 to 192.168.5.128:7003
  17. M: 3cbed89c47ca14b3d1eb11dd2f7525fa6cb4fcd7 192.168.5.128:7001
  18. slots:0-5460 (5461 slots) master
  19. M: 27d069e1b4d459a92b6cc9a1c92ad46ea00cb61d 192.168.5.128:7002
  20. slots:5461-10922 (5462 slots) master
  21. M: d7d28caadfdc4161261305f2d2baf55d2d8f4221 192.168.5.128:7003
  22. slots:10923-16383 (5461 slots) master
  23. S: f124b72c0421c7514f44668d30761d075e42643d 192.168.5.128:7004
  24. replicates 3cbed89c47ca14b3d1eb11dd2f7525fa6cb4fcd7
  25. S: 8cf60c085a58b60557a887a5e8451ce38e6b54fa 192.168.5.128:7005
  26. replicates 27d069e1b4d459a92b6cc9a1c92ad46ea00cb61d
  27. S: 05ad0eb9b5f839771b09dc18192909d5fa1f893e 192.168.5.128:7006
  28. replicates d7d28caadfdc4161261305f2d2baf55d2d8f4221
  29. Can I set the above configuration? (type 'yes' to accept): yes
  30. >>> Nodes configuration updated
  31. >>> Assign a different config epoch to each node
  32. >>> Sending CLUSTER MEET messages to join the cluster
  33. Waiting for the cluster to join......
  34. >>> Performing Cluster Check (using node 192.168.5.128:7001)
  35. M: 3cbed89c47ca14b3d1eb11dd2f7525fa6cb4fcd7 192.168.5.128:7001
  36. slots:0-5460 (5461 slots) master
  37. M: 27d069e1b4d459a92b6cc9a1c92ad46ea00cb61d 192.168.5.128:7002
  38. slots:5461-10922 (5462 slots) master
  39. M: d7d28caadfdc4161261305f2d2baf55d2d8f4221 192.168.5.128:7003
  40. slots:10923-16383 (5461 slots) master
  41. M: f124b72c0421c7514f44668d30761d075e42643d 192.168.5.128:7004
  42. slots: (0 slots) master
  43. replicates 3cbed89c47ca14b3d1eb11dd2f7525fa6cb4fcd7
  44. M: 8cf60c085a58b60557a887a5e8451ce38e6b54fa 192.168.5.128:7005
  45. slots: (0 slots) master
  46. replicates 27d069e1b4d459a92b6cc9a1c92ad46ea00cb61d
  47. M: 05ad0eb9b5f839771b09dc18192909d5fa1f893e 192.168.5.128:7006
  48. slots: (0 slots) master
  49. replicates d7d28caadfdc4161261305f2d2baf55d2d8f4221
  50. [OK] All nodes agree about slots configuration.
  51. >>> Check for open slots...
  52. >>> Check slots coverage...
  53. [OK] All 16384 slots covered.
  54. [root@itheima redis-cluster]#

8.5、连接集群

  [root@itheima 7001]# ./redis-cli -h 192.168.5.128 -p 7001 –c 
  -c:指定是集群连接 

8.6、查看集群信息的命令

  • 查看集群信息
  1. 192.168.5.128:7002> cluster info
  2. cluster_state:ok
  3. cluster_slots_assigned:16384
  4. cluster_slots_ok:16384
  5. cluster_slots_pfail:0
  6. cluster_slots_fail:0
  7. cluster_known_nodes:6
  8. cluster_size:3
  9. cluster_current_epoch:6
  10. cluster_my_epoch:2
  11. cluster_stats_messages_sent:1837
  12. cluster_stats_messages_received:1837
  13. 192.168.5.128:7002>
  • 查看集群中的节点
  1. 192.168.5.128:7002> cluster nodes
  2. d7d28caadfdc4161261305f2d2baf55d2d8f4221 192.168.5.128:7003 master - 0 1541263366376 3 connected 10923-16383
  3. f124b72c0421c7514f44668d30761d075e42643d 192.168.5.128:7004 slave 3cbed89c47ca14b3d1eb11dd2f7525fa6cb4fcd7 0 1541263372425 4 connected
  4. 05ad0eb9b5f839771b09dc18192909d5fa1f893e 192.168.5.128:7006 slave d7d28caadfdc4161261305f2d2baf55d2d8f4221 0 1541263371417 6 connected
  5. 3cbed89c47ca14b3d1eb11dd2f7525fa6cb4fcd7 192.168.5.128:7001 master - 0 1541263370402 1 connected 0-5460
  6. 8cf60c085a58b60557a887a5e8451ce38e6b54fa 192.168.5.128:7005 slave 27d069e1b4d459a92b6cc9a1c92ad46ea00cb61d 0 1541263369396 5 connected
  7. 27d069e1b4d459a92b6cc9a1c92ad46ea00cb61d 192.168.5.128:7002 myself,master - 0 0 2 connected 5461-10922
  8. 192.168.5.128:7002>

8.7、维护集群节点(自学)

8.7.1、添加主节点

  • 集群创建成功后可以向集群中添加节点,下面演示是添加一个master主节点。
  • 准备工作:1) 先复制出一个7007的机器;2) 如果存在持久化文件和节点配置文件,就删除掉;3) 修改机器7007的端口;4) 启动机器7007 
    [root@itheima redis-cluster]# cp 7001/ 7007 -r 
    [root@itheima redis-cluster]# cd 7007/ 
    [root@itheima 7007]# rm -rf appendonly.aof dump.rdb nodes.conf 
    [root@itheima redis-cluster]# cd 7007/ 
    [root@itheima 7007]# vim redis.conf 
    [root@itheima 7007]# ./redis-server redis.conf
  • 添加7007结点作为新主节点 
      命令:[root@itheima redis-cluster]# ./redis-trib.rb add-node 192.168.5.128:7007 192.168.5.128:7001
  • 示例如下:
  1. [root@itheima redis-cluster]# ./redis-trib.rb add-node 192.168.5.128:7007 192.168.5.128:7001
  2. >>> Adding node 192.168.5.128:7007 to cluster 192.168.5.128:7001
  3. Connecting to node 192.168.5.128:7001: OK
  4. Connecting to node 192.168.5.128:7006: OK
  5. Connecting to node 192.168.5.128:7004: OK
  6. Connecting to node 192.168.5.128:7002: OK
  7. Connecting to node 192.168.5.128:7005: OK
  8. Connecting to node 192.168.5.128:7003: OK
  9. >>> Performing Cluster Check (using node 192.168.5.128:7001)
  10. M: 3cbed89c47ca14b3d1eb11dd2f7525fa6cb4fcd7 192.168.5.128:7001
  11. slots:0-5460 (5461 slots) master
  12. 1 additional replica(s)
  13. S: 05ad0eb9b5f839771b09dc18192909d5fa1f893e 192.168.5.128:7006
  14. slots: (0 slots) slave
  15. replicates d7d28caadfdc4161261305f2d2baf55d2d8f4221
  16. S: f124b72c0421c7514f44668d30761d075e42643d 192.168.5.128:7004
  17. slots: (0 slots) slave
  18. replicates 3cbed89c47ca14b3d1eb11dd2f7525fa6cb4fcd7
  19. M: 27d069e1b4d459a92b6cc9a1c92ad46ea00cb61d 192.168.5.128:7002
  20. slots:5461-10922 (5462 slots) master
  21. 1 additional replica(s)
  22. S: 8cf60c085a58b60557a887a5e8451ce38e6b54fa 192.168.5.128:7005
  23. slots: (0 slots) slave
  24. replicates 27d069e1b4d459a92b6cc9a1c92ad46ea00cb61d
  25. M: d7d28caadfdc4161261305f2d2baf55d2d8f4221 192.168.5.128:7003
  26. slots:10923-16383 (5461 slots) master
  27. 1 additional replica(s)
  28. [OK] All nodes agree about slots configuration.
  29. >>> Check for open slots...
  30. >>> Check slots coverage...
  31. [OK] All 16384 slots covered.
  32. Connecting to node 192.168.5.128:7007: OK
  33. >>> Send CLUSTER MEET to node 192.168.5.128:7007 to make it join the cluster.
  34. [OK] New node added correctly.
  35. [root@itheima redis-cluster]#
  • 查看集群结点,发现主节点7007已添加到集群中 
  • 但是我们发现新的集群主节点没有槽,所以添加完主节点需要对主节点进行hash槽分配,这样该主节才可以存储数据。

8.7.2、hash槽重新分配

  • 添加完主节点需要对主节点进行hash槽分配,这样该主节才可以存储数据。
  • 查看集群中槽占用情况
  • redis集群有16384个槽,集群中的每个结点分配自已槽,通过查看集群结点可以看到槽占用情况。 
  • 给刚添加的主节点7007分配槽 
    第一步:连接上集群(连接集群中任意一个可用结点都行) 
    [root@itheima redis-cluster]# # ./redis-trib.rb reshard 192.168.5.128:7001 
    第二步:输入要分配的槽数量、输入接收槽的结点id和输入源结点id,回车 

    第五步:输入yes开始移动槽到目标结点id 
     
    第六步:查看分配后主节点7007的槽 

8.7.3、添加从节点

  • 集群创建成功后可以向集群中添加节点,下面是添加一个slave从节点。
  • 添加7008从结点,将7008作为7007的从结点。 
    • 准备工作:1) 先复制出一个7008的机器;2) 如果存在持久化文件和节点配置文件,就删除掉;3) 修改机器7008的端口;4) 启动机器7008 
      [root@itheima redis-cluster]# cp 7001/ 7008 -r 
      [root@itheima redis-cluster]# cd 7008/ 
      [root@itheima 7008]# rm -rf appendonly.aof dump.rdb nodes.conf 
      [root@itheima redis-cluster]# cd 7008/ 
      [root@itheima 7008]# vim redis.conf 
      [root@itheima 7008]# ./redis-server redis.conf
  • 添加7008从结点,将7008作为7007的从结点 
      命令:./redis-trib.rb add-node –slave –master-id 主节点id 新节点的ip和端口 旧节点ip和端口 
      命令:[root@itheima redis-cluster]# ./redis-trib.rb add-node –slave –master-id 26630461d8a63a7398e3f43b7366014c72a6a7ef 192.168.5.128:7008 192.168.5.128:7007 
    • 示例如下:
  1. [root@itheima redis-cluster]# ./redis-trib.rb add-node --slave --master-id 26630461d8a63a7398e3f43b7366014c72a6a7ef 192.168.5.128:7008 192.168.5.128:7007
  2. >>> Adding node 192.168.5.128:7008 to cluster 192.168.5.128:7007
  3. Connecting to node 192.168.5.128:7007: OK
  4. Connecting to node 192.168.5.128:7001: OK
  5. Connecting to node 192.168.5.128:7003: OK
  6. Connecting to node 192.168.5.128:7005: OK
  7. Connecting to node 192.168.5.128:7004: OK
  8. Connecting to node 192.168.5.128:7006: OK
  9. Connecting to node 192.168.5.128:7002: OK
  10. >>> Performing Cluster Check (using node 192.168.5.128:7007)
  11. M: 26630461d8a63a7398e3f43b7366014c72a6a7ef 192.168.5.128:7007
  12. slots:0-165,5461-5627,10923-11088 (499 slots) master
  13. 0 additional replica(s)
  14. M: 3cbed89c47ca14b3d1eb11dd2f7525fa6cb4fcd7 192.168.5.128:7001
  15. slots:166-5460 (5295 slots) master
  16. 1 additional replica(s)
  17. M: d7d28caadfdc4161261305f2d2baf55d2d8f4221 192.168.5.128:7003
  18. slots:11089-16383 (5295 slots) master
  19. 1 additional replica(s)
  20. S: 8cf60c085a58b60557a887a5e8451ce38e6b54fa 192.168.5.128:7005
  21. slots: (0 slots) slave
  22. replicates 27d069e1b4d459a92b6cc9a1c92ad46ea00cb61d
  23. S: f124b72c0421c7514f44668d30761d075e42643d 192.168.5.128:7004
  24. slots: (0 slots) slave
  25. replicates 3cbed89c47ca14b3d1eb11dd2f7525fa6cb4fcd7
  26. S: 05ad0eb9b5f839771b09dc18192909d5fa1f893e 192.168.5.128:7006
  27. slots: (0 slots) slave
  28. replicates d7d28caadfdc4161261305f2d2baf55d2d8f4221
  29. M: 27d069e1b4d459a92b6cc9a1c92ad46ea00cb61d 192.168.5.128:7002
  30. slots:5628-10922 (5295 slots) master
  31. 1 additional replica(s)
  32. [OK] All nodes agree about slots configuration.
  33. >>> Check for open slots...
  34. >>> Check slots coverage...
  35. [OK] All 16384 slots covered.
  36. Connecting to node 192.168.5.128:7008: OK
  37. >>> Send CLUSTER MEET to node 192.168.5.128:7008 to make it join the cluster.
  38. Waiting for the cluster to join.
  39. >>> Configure node as replica of 192.168.5.128:7007.
  40. [OK] New node added correctly.
  • 注意:如果原来该结点在集群中的配置信息已经生成到cluster-config-file指定的配置文件中(如果cluster-config-file没有指定则默认为nodes.conf),这时可能会报错:
  1. [ERR] Node XXXXXX is not empty. Either the node already knows other nodes (check with CLUSTER NODES) or contains some key in database 0
  • 解决方法:是删除生成的配置文件nodes.conf,删除后再执行./redis-trib.rb add-node 指令
  • 查看集群中的结点,刚添加的7008为7007的从节点: 

8.7.4、删除结点

  • 命令:./redis-trib.rb del-node 192.168.5.128:7003 d7d28caadfdc4161261305f2d2baf55d2d8f4221
  • 删除已经占有hash槽的结点(即主节点)会失败,报错如下: 
    [ERR] Node 192.168.5.128:7003 is not empty! Reshard data away and try again.
  • 需要将该结点(主节点)占用的hash槽分配出去后再删除(参考hash槽重新分配章节)。

示例如下: 
删除从节点:

  1. [root@itheima redis-cluster]# ./redis-trib.rb del-node 192.168.5.128:7005 8cf60c085a58b60557a887a5e8451ce38e6b54fa
  2. >>> Removing node 8cf60c085a58b60557a887a5e8451ce38e6b54fa from cluster 192.168.5.128:7005
  3. Connecting to node 192.168.5.128:7005: OK
  4. Connecting to node 192.168.5.128:7008: OK
  5. Connecting to node 192.168.5.128:7004: OK
  6. Connecting to node 192.168.5.128:7007: OK
  7. Connecting to node 192.168.5.128:7006: OK
  8. Connecting to node 192.168.5.128:7003: OK
  9. Connecting to node 192.168.5.128:7001: OK
  10. Connecting to node 192.168.5.128:7002: OK
  11. >>> Sending CLUSTER FORGET messages to the cluster...
  12. >>> SHUTDOWN the node.
  13. [root@itheima redis-cluster]#

删除主节点:

  1. [root@itheima redis-cluster]# ./redis-trib.rb del-node 192.168.5.128:7003 d7d28caadfdc4161261305f2d2baf55d2d8f4221
  2. >>> Removing node d7d28caadfdc4161261305f2d2baf55d2d8f4221 from cluster 192.168.5.128:7003
  3. Connecting to node 192.168.5.128:7003: OK
  4. Connecting to node 192.168.5.128:7001: OK
  5. Connecting to node 192.168.5.128:7008: OK
  6. Connecting to node 192.168.5.128:7007: OK
  7. Connecting to node 192.168.5.128:7004: OK
  8. Connecting to node 192.168.5.128:7002: OK
  9. Connecting to node 192.168.5.128:7006: OK
  10. [ERR] Node 192.168.5.128:7003 is not empty! Reshard data away and try again.
  11. [root@itheima redis-cluster]#

9、Jedis连接Redis集群

9.1、防火墙配置

  • CentOS7默认的防火墙不是iptables,而是firewalld。我们可以试一下systemctl stop firewalld关闭防火墙,但是不推荐该方式。
  • 如果是iptables,就vim /etc/sysconfig/iptables修改配置即可。详细的过程,博主以后会整理补充上。
  • 本博主的是CentOS7,防火墙使用的是firewalld,我们使用命令的方式来添加端口(修改后需要重启firewalld服务): 
      [root@itheima ~]# cd /etc/firewalld/zones/ 
      [root@itheima zones]# firewall-cmd –permanent –add-port=6379/tcp 
      [root@itheima zones]# service firewalld restart 
      Redirecting to /bin/systemctl restart firewalld.service 
      [root@itheima zones]# 

9.2、代码实现

  • 创建JedisCluster类连接redis集群。
  1. /**
  2. * Jedis连接Redis集群
  3. */
  4. @Test
  5. public void testJedisCluster1() {
  6. Set<HostAndPort> nodes = new HashSet<>();
  7. nodes.add(new HostAndPort("192.168.5.128", 7001));
  8. nodes.add(new HostAndPort("192.168.5.128", 7002));
  9. nodes.add(new HostAndPort("192.168.5.128", 7003));
  10. nodes.add(new HostAndPort("192.168.5.128", 7004));
  11. nodes.add(new HostAndPort("192.168.5.128", 7005));
  12. nodes.add(new HostAndPort("192.168.5.128", 7006));
  13. // 创建JedisCluster对象,在系统中是单例存在的
  14. JedisCluster jedisCluster = new JedisCluster(nodes);
  15. // 执行JedisCluster对象中的方法,方法和redis中的一一对应
  16. jedisCluster.set("cluster-test", "Jedis connects Redis cluster test");
  17. String result = jedisCluster.get("cluster-test");
  18. System.out.println(result);
  19. // 程序结束时需要关闭JedisCluster对象
  20. jedisCluster.close();
  21. }

9.3、使用spring实现Jedis连接Redis集群

  • 配置applicationContext.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  8. http://www.springframework.org/schema/mvc
  9. http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  10. http://www.springframework.org/schema/context
  11. http://www.springframework.org/schema/context/spring-context-3.2.xsd
  12. http://www.springframework.org/schema/aop
  13. http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
  14. http://www.springframework.org/schema/tx
  15. http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
  16. <!-- 连接池配置 -->
  17. <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
  18. <!-- 最大连接数 -->
  19. <property name="maxTotal" value="30" />
  20. <!-- 最大空闲连接数 -->
  21. <property name="maxIdle" value="10" />
  22. <!-- 每次释放连接的最大数目 -->
  23. <property name="numTestsPerEvictionRun" value="1024" />
  24. <!-- 释放连接的扫描间隔(毫秒) -->
  25. <property name="timeBetweenEvictionRunsMillis" value="30000" />
  26. <!-- 连接最小空闲时间 -->
  27. <property name="minEvictableIdleTimeMillis" value="1800000" />
  28. <!-- 连接空闲多久后释放, 当空闲时间>该值 且 空闲连接>最大空闲连接数 时直接释放 -->
  29. <property name="softMinEvictableIdleTimeMillis" value="10000" />
  30. <!-- 获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1 -->
  31. <property name="maxWaitMillis" value="1500" />
  32. <!-- 在获取连接的时候检查有效性, 默认false -->
  33. <property name="testOnBorrow" value="true" />
  34. <!-- 在空闲时检查有效性, 默认false -->
  35. <property name="testWhileIdle" value="true" />
  36. <!-- 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true -->
  37. <property name="blockWhenExhausted" value="false" />
  38. </bean>
  39. <!-- redis集群 -->
  40. <bean id="jedisCluster" class="redis.clients.jedis.JedisCluster">
  41. <constructor-arg index="0">
  42. <set>
  43. <bean class="redis.clients.jedis.HostAndPort">
  44. <constructor-arg index="0" value="192.168.5.128"></constructor-arg>
  45. <constructor-arg index="1" value="7001"></constructor-arg>
  46. </bean>
  47. <bean class="redis.clients.jedis.HostAndPort">
  48. <constructor-arg index="0" value="192.168.5.128"></constructor-arg>
  49. <constructor-arg index="1" value="7002"></constructor-arg>
  50. </bean>
  51. <bean class="redis.clients.jedis.HostAndPort">
  52. <constructor-arg index="0" value="192.168.5.128"></constructor-arg>
  53. <constructor-arg index="1" value="7003"></constructor-arg>
  54. </bean>
  55. <bean class="redis.clients.jedis.HostAndPort">
  56. <constructor-arg index="0" value="192.168.5.128"></constructor-arg>
  57. <constructor-arg index="1" value="7004"></constructor-arg>
  58. </bean>
  59. <bean class="redis.clients.jedis.HostAndPort">
  60. <constructor-arg index="0" value="192.168.5.128"></constructor-arg>
  61. <constructor-arg index="1" value="7005"></constructor-arg>
  62. </bean>
  63. <bean class="redis.clients.jedis.HostAndPort">
  64. <constructor-arg index="0" value="192.168.5.128"></constructor-arg>
  65. <constructor-arg index="1" value="7006"></constructor-arg>
  66. </bean>
  67. </set>
  68. </constructor-arg>
  69. <constructor-arg index="1" ref="jedisPoolConfig"></constructor-arg>
  70. </bean>
  71. </beans>
  • 测试代码
    1. private ApplicationContext applicationContext;
    2. @Before
    3. public void init() {
    4. applicationContext = new ClassPathXmlApplicationContext(
    5. "classpath:applicationContext.xml");
    6. }
    7. /**
    8. * 使用spring实现Jedis连接Redis集群
    9. */
    10. @Test
    11. public void testJedisCluster2() {
    12. JedisCluster jedisCluster = (JedisCluster) applicationContext.getBean("jedisCluster");
    13. jedisCluster.set("name", "xiaoyi");
    14. String value = jedisCluster.get("name");
    15. System.out.println(value);
    16. }
posted @ 2018-12-08 09:21  New_Journey  阅读(159)  评论(0编辑  收藏  举报