redis客户端redisson实战

    

redis 学习问题总结

http://aperise.iteye.com/blog/2310639

ehcache memcached redis 缓存技术总结

http://aperise.iteye.com/blog/2296219

redis-stat 离线安装

http://aperise.iteye.com/blog/2310254

redis  cluster 非ruby方式启动

http://aperise.iteye.com/blog/2310254

redis-sentinel安装部署

http://aperise.iteye.com/blog/2342693

spring-data-redis使用

 http://aperise.iteye.com/blog/2342615

redis客户端redisson实战

http://blog.csdn.net/zilong_zilong/article/details/78252037

redisson-2.10.4源代码分析

http://blog.csdn.net/zilong_zilong/article/details/78609423

tcmalloc jemalloc libc选择

http://blog.csdn.net/u010994304/article/details/49906819

 redis客户端redisson实战

1.前言

    Redisson是一个基于java编程框架netty进行扩展了的redis,想了解Redisson源码首先你必须熟悉netty网络编程框架

    Redisson目前分开源版本商业版(Redisson PRO),所以选择的时候请谨慎(Map)和集(Set)数据分片功能仅限于Redisson PRO版本才有,另外Redis部署工具和集群管理工具功能仅限于Redisson PRO版本才有。关于商业版和开源版本的区别和商业版收费标准详见官网(https://redisson.pro/)  

 

 

 

2.maven项目集成redisson

    根据自己JDK环境,JDK 1.8+以上请选择3.5.4版本,JDK 1.6+以上请选择2.10.4版本 

[xml] view plain copy

  1. <!-- JDK 1.8+ compatible -->  
  2. <dependency>  
  3.    <groupId>org.redisson</groupId>  
  4.    <artifactId>redisson</artifactId>  
  5.    <version>3.5.4</version>  
  6. </dependency>    
  7.   
  8. <!-- JDK 1.6+ compatible -->  
  9. <dependency>  
  10.    <groupId>org.redisson</groupId>  
  11.    <artifactId>redisson</artifactId>  
  12.    <version>2.10.4</version>  
  13. </dependency>  

 

3.利用redisson API操作各种redis部署的服务端

    redis的部署方式有单节点部署、哨兵方式部署、集群方式部署3种方式,这3中方式都使用的是原生的redis;

    基于单节点部署为了保证数据的备份,一般会添加一个节点作为slave来备份master节点上的数据,这里就衍生出了主从部署方式;

    云服务商像阿里云、微软云和亚马逊云都基于原生redis做了高可用部署,为了能连接云服务商的redis服务,这里redisson也提供了API操作方式。

    下面以向redis服务端进行操作set key value为例进行说明如何使用redisson的API

 

    3.1 单节点部署方式(standalone)


    (1)纯java操作

 
  1. //创建配置

  2. Config config = new Config();

  3.  
  4. //指定编码,默认编码为org.redisson.codec.JsonJacksonCodec

  5. //之前使用的spring-data-redis,用的客户端jedis,编码为org.springframework.data.redis.serializer.StringRedisSerializer

  6. //改用redisson后为了之间数据能兼容,这里修改编码为org.redisson.client.codec.StringCodec

  7. config.setCodec(new org.redisson.client.codec.StringCodec());

  8.  
  9. //指定使用单节点部署方式

  10. config.useSingleServer().setAddress("redis://127.0.0.1:6379");

  11.  
  12. //config.setPassword("password")//设置密码

  13. config.setConnectionPoolSize(500)//设置对于master节点的连接池中连接数最大为500

  14. config.setIdleConnectionTimeout(10000)//如果当前连接池里的连接数量超过了最小空闲连接数,而同时有连接空闲时间超过了该数值,那么这些连接将会自动被关闭,并从连接池里去掉。时间单位是毫秒。

  15. config.setConnectTimeout(30000)//同任何节点建立连接时的等待超时。时间单位是毫秒。

  16. config.setTimeout(3000)//等待节点回复命令的时间。该时间从命令发送成功时开始计时。

  17. config.setPingTimeout(30000)

  18. config.setReconnectionTimeout(3000)//当与某个节点的连接断开时,等待与其重新建立连接的时间间隔。时间单位是毫秒。

  19.  
  20. //创建客户端(发现创建RedissonClient非常耗时,基本在2秒-4秒左右)

  21. RedissonClient redisson = Redisson.create(config);

  22.  
  23. //首先获取redis中的key-value对象,key不存在没关系

  24. RBucket<String> keyObject = redisson.getBucket("key");

  25. //如果key存在,就设置key的值为新值value

  26. //如果key不存在,就设置key的值为value

  27. keyObject.set("value");

  28.  
  29. //最后关闭RedissonClient

  30. redisson.shutdown();

    (2)spring集成操作  

    pom.xml

[xml] view plain copy

  1. <!--redisson-->  
  2. <dependency>  
  3.     <groupId>org.redisson</groupId>  
  4.     <artifactId>redisson</artifactId>  
  5.     <version>2.10.4</version>  
  6. </dependency>  
  7. <!--spring-->  
  8. <dependency>  
  9.     <groupId>org.springframework</groupId>  
  10.     <artifactId>spring-core</artifactId>  
  11.     <version>4.2.8.RELEASE</version>  
  12. </dependency>  
  13. <dependency>  
  14.     <groupId>org.springframework</groupId>  
  15.     <artifactId>spring-beans</artifactId>  
  16.     <version>4.2.8.RELEASE</version>  
  17. </dependency>  
  18. <dependency>  
  19.     <groupId>org.springframework</groupId>  
  20.     <artifactId>spring-context</artifactId>  
  21.     <version>4.2.8.RELEASE</version>  
  22. </dependency>  

    spring-redisson.xml

[xml] view plain copy

  1. <beans xmlns="http://www.springframework.org/schema/beans"    
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     
  3.     xmlns:context="http://www.springframework.org/schema/context"    
  4.     xmlns:redisson="http://redisson.org/schema/redisson"    
  5.     xsi:schemaLocation="    
  6.        http://www.springframework.org/schema/beans    
  7.        http://www.springframework.org/schema/beans/spring-beans.xsd    
  8.        http://www.springframework.org/schema/context    
  9.        http://www.springframework.org/schema/context/spring-context.xsd    
  10.        http://redisson.org/schema/redisson    
  11.        http://redisson.org/schema/redisson/redisson.xsd">    
  12.     <bean id="stringCodec" class="org.redisson.client.codec.StringCodec"></bean>  
  13.     <redisson:client id="standalone"   
  14.                      name="aliasName1,aliasName2"  
  15.                      codec-ref="stringCodec">    
  16.         <redisson:single-server address="redis://127.0.0.1:6379"  
  17.                                 connection-pool-size="500"  
  18.                                 idle-connection-timeout="10000"  
  19.                                 connect-timeout="10000"  
  20.                                 timeout="3000"  
  21.                                 ping-timeout="30000"  
  22.                                 reconnection-timeout="30000"  
  23.                                 database="0"/>    
  24.     </redisson:client>    
  25. </beans>    

    SpringRedissonTest.java

 
  1. import org.redisson.api.RBucket;

  2. import org.redisson.api.RedissonClient;

  3. import org.springframework.context.ApplicationContext;

  4. import org.springframework.context.support.ClassPathXmlApplicationContext;

  5. public class SpringRedissonTest {

  6. public static void main(String[] args) {

  7. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring-redisson.xml");

  8. RedissonClient redisson = (RedissonClient) applicationContext.getBean("standalone");

  9. // 首先获取redis中的key-value对象,key不存在没关系

  10. RBucket<String> keyObject = redisson.getBucket("key");

  11. // 如果key存在,就设置key的值为新值value

  12. // 如果key不存在,就设置key的值为value

  13. keyObject.set("value");

  14. }

  15. }

 

    3.2 哨兵部署方式(sentinel)


    (1)纯java操作

 
  1. //创建配置

  2. Config config = new Config();

  3.  
  4. //指定编码,默认编码为org.redisson.codec.JsonJacksonCodec

  5. //之前使用的spring-data-redis,用的客户端jedis,编码为org.springframework.data.redis.serializer.StringRedisSerializer

  6. //改用redisson后为了之间数据能兼容,这里修改编码为org.redisson.client.codec.StringCodec

  7. config.setCodec(new org.redisson.client.codec.StringCodec());

  8.  
  9. //指定使用哨兵部署方式

  10. config.useSentinelServers()

  11. //设置sentinel.conf配置里的sentinel别名

  12. //比如sentinel.conf里配置为sentinel monitor my-sentinel-name 127.0.0.1 6379 2,那么这里就配置my-sentinel-name

  13.     .setMasterName("my-sentinel-name")

  14.     //这里设置sentinel节点的服务IP和端口,sentinel是采用Paxos拜占庭协议,一般sentinel至少3个节点

  15.     //记住这里不是配置redis节点的服务端口和IP,sentinel会自己把请求转发给后面monitor的redis节点

  16.     .addSentinelAddress("redis://127.0.0.1:26379")

  17.     .addSentinelAddress("redis://127.0.0.1:26389")

  18.     .addSentinelAddress("redis://127.0.0.1:26399");

  19.     

  20. //config.setPassword("password")//设置密码

  21. config.setMasterConnectionPoolSize(500)//设置对于master节点的连接池中连接数最大为500

  22. config.setSlaveConnectionPoolSize(500)//设置对于slave节点的连接池中连接数最大为500

  23. config.setIdleConnectionTimeout(10000)//如果当前连接池里的连接数量超过了最小空闲连接数,而同时有连接空闲时间超过了该数值,那么这些连接将会自动被关闭,并从连接池里去掉。时间单位是毫秒。

  24. config.setConnectTimeout(30000)//同任何节点建立连接时的等待超时。时间单位是毫秒。

  25. config.setTimeout(3000)//等待节点回复命令的时间。该时间从命令发送成功时开始计时。

  26. config.setPingTimeout(30000)

  27. config.setReconnectionTimeout(3000)//当与某个节点的连接断开时,等待与其重新建立连接的时间间隔。时间单位是毫秒。

  28.  
  29. //创建客户端(发现这一非常耗时,基本在2秒-4秒左右)

  30. RedissonClient redisson = Redisson.create(config);

  31. //首先获取redis中的key-value对象,key不存在没关系

  32. RBucket<String> keyObject = redisson.getBucket("key");

  33. //如果key存在,就设置key的值为新值value

  34. //如果key不存在,就设置key的值为value

  35. keyObject.set("value");

  36.  
  37. //最后关闭RedissonClient

  38. redisson.shutdown();

    (2)spring集成操作

    pom.xml

[xml] view plain copy

  1. <!--redisson-->  
  2. <dependency>  
  3.     <groupId>org.redisson</groupId>  
  4.     <artifactId>redisson</artifactId>  
  5.     <version>2.10.4</version>  
  6. </dependency>  
  7. <!--spring-->  
  8. <dependency>  
  9.     <groupId>org.springframework</groupId>  
  10.     <artifactId>spring-core</artifactId>  
  11.     <version>4.2.8.RELEASE</version>  
  12. </dependency>  
  13. <dependency>  
  14.     <groupId>org.springframework</groupId>  
  15.     <artifactId>spring-beans</artifactId>  
  16.     <version>4.2.8.RELEASE</version>  
  17. </dependency>  
  18. <dependency>  
  19.     <groupId>org.springframework</groupId>  
  20.     <artifactId>spring-context</artifactId>  
  21.     <version>4.2.8.RELEASE</version>  
  22. </dependency>  

    spring-redisson.xml

[xml] view plain copy

  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  3.     xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:redisson="http://redisson.org/schema/redisson"  
  5.     xsi:schemaLocation="  
  6.        http://www.springframework.org/schema/beans  
  7.        http://www.springframework.org/schema/beans/spring-beans.xsd  
  8.        http://www.springframework.org/schema/context  
  9.        http://www.springframework.org/schema/context/spring-context.xsd  
  10.        http://redisson.org/schema/redisson  
  11.        http://redisson.org/schema/redisson/redisson.xsd">  
  12. <bean id="stringCodec" class="org.redisson.client.codec.StringCodec"></bean>  
  13. <redisson:client id="sentinel" codec-ref="stringCodec">  
  14.     <redisson:sentinel-servers master-name="my-sentinel-name"  
  15.                                 slaveConnectionPoolSize="500"  
  16.                                 masterConnectionPoolSize="500"  
  17.                                 idle-connection-timeout="10000"  
  18.                                 connect-timeout="10000"  
  19.                                 timeout="3000"  
  20.                                 ping-timeout="1000"  
  21.                                 reconnection-timeout="3000"  
  22.                                 database="0">  
  23.         <redisson:sentinel-address value="redis://127.0.0.1:26379" />  
  24.         <redisson:sentinel-address value="redis://127.0.0.1:26389" />  
  25.         <redisson:sentinel-address value="redis://127.0.0.1:26399" />  
  26.     </redisson:sentinel-servers>  
  27. </redisson:client>  
  28. </beans>  

    SpringRedissonTest.java

 
  1. import org.redisson.api.RBucket;

  2. import org.redisson.api.RedissonClient;

  3. import org.springframework.context.ApplicationContext;

  4. import org.springframework.context.support.ClassPathXmlApplicationContext;

  5. public class SpringRedissonTest {

  6. public static void main(String[] args) {

  7. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring-redisson.xml");

  8. RedissonClient redisson = (RedissonClient) applicationContext.getBean("sentinel");

  9. // 首先获取redis中的key-value对象,key不存在没关系

  10. RBucket<String> keyObject = redisson.getBucket("key");

  11. // 如果key存在,就设置key的值为新值value

  12. // 如果key不存在,就设置key的值为value

  13. keyObject.set("value");

  14. }

  15. }

 

    3.3 集群方式(cluster)


    (1)纯java操作

 
  1. //创建配置

  2. Config config = new Config();

  3.  
  4. //指定编码,默认编码为org.redisson.codec.JsonJacksonCodec

  5. //之前使用的spring-data-redis,用的客户端jedis,编码为org.springframework.data.redis.serializer.StringRedisSerializer

  6. //改用redisson后为了之间数据能兼容,这里修改编码为org.redisson.client.codec.StringCodec

  7. config.setCodec(new org.redisson.client.codec.StringCodec());

  8.  
  9. //指定使用集群部署方式

  10. config.useClusterServers()

  11. // 集群状态扫描间隔时间,单位是毫秒

  12.     .setScanInterval(2000) 

  13.     //cluster方式至少6个节点(3主3从,3主做sharding,3从用来保证主宕机后可以高可用)

  14.     .addNodeAddress("redis://127.0.0.1:6379" )

  15.     .addNodeAddress("redis://127.0.0.1:6380")

  16.     .addNodeAddress("redis://127.0.0.1:6381")

  17.     .addNodeAddress("redis://127.0.0.1:6382")

  18.     .addNodeAddress("redis://127.0.0.1:6383")

  19.     .addNodeAddress("redis://127.0.0.1:6384");

  20.     

  21. //config.setPassword("password")//设置密码

  22. config.setMasterConnectionPoolSize(500)//设置对于master节点的连接池中连接数最大为500

  23. config.setSlaveConnectionPoolSize(500)//设置对于slave节点的连接池中连接数最大为500

  24. config.setIdleConnectionTimeout(10000)//如果当前连接池里的连接数量超过了最小空闲连接数,而同时有连接空闲时间超过了该数值,那么这些连接将会自动被关闭,并从连接池里去掉。时间单位是毫秒。

  25. config.setConnectTimeout(30000)//同任何节点建立连接时的等待超时。时间单位是毫秒。

  26. config.setTimeout(3000)//等待节点回复命令的时间。该时间从命令发送成功时开始计时。

  27. config.setPingTimeout(30000)

  28. config.setReconnectionTimeout(3000)//当与某个节点的连接断开时,等待与其重新建立连接的时间间隔。时间单位是毫秒。

  29.  
  30. //创建客户端(发现创建RedissonClient非常耗时,基本在2秒-4秒左右)

  31. RedissonClient redisson = Redisson.create(config);

  32.  
  33. //首先获取redis中的key-value对象,key不存在没关系

  34. RBucket<String> keyObject = redisson.getBucket("key");

  35. //如果key存在,就设置key的值为新值value

  36. //如果key不存在,就设置key的值为value

  37. keyObject.set("value");

  38.  
  39. //最后关闭RedissonClient

  40. redisson.shutdown();

    (2)spring集成操作

    pom.xml

[xml] view plain copy

  1. <!--redisson-->  
  2. <dependency>  
  3.     <groupId>org.redisson</groupId>  
  4.     <artifactId>redisson</artifactId>  
  5.     <version>2.10.4</version>  
  6. </dependency>  
  7. <!--spring-->  
  8. <dependency>  
  9.     <groupId>org.springframework</groupId>  
  10.     <artifactId>spring-core</artifactId>  
  11.     <version>4.2.8.RELEASE</version>  
  12. </dependency>  
  13. <dependency>  
  14.     <groupId>org.springframework</groupId>  
  15.     <artifactId>spring-beans</artifactId>  
  16.     <version>4.2.8.RELEASE</version>  
  17. </dependency>  
  18. <dependency>  
  19.     <groupId>org.springframework</groupId>  
  20.     <artifactId>spring-context</artifactId>  
  21.     <version>4.2.8.RELEASE</version>  
  22. </dependency>  

    spring-redisson.xml

[xml] view plain copy

  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2. <span style="white-space:pre">  </span>xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  3. <span style="white-space:pre">  </span>xmlns:context="http://www.springframework.org/schema/context"  
  4. <span style="white-space:pre">  </span>xmlns:redisson="http://redisson.org/schema/redisson"  
  5. <span style="white-space:pre">  </span>xsi:schemaLocation="  
  6.        http://www.springframework.org/schema/beans  
  7.        http://www.springframework.org/schema/beans/spring-beans.xsd  
  8.        http://www.springframework.org/schema/context  
  9.        http://www.springframework.org/schema/context/spring-context.xsd  
  10.        http://redisson.org/schema/redisson  
  11.        http://redisson.org/schema/redisson/redisson.xsd">  
  12.     <bean id="stringCodec" class="org.redisson.client.codec.StringCodec"></bean>  
  13. <span style="white-space:pre">  </span><redisson:client id="cluster" codec-ref="stringCodec">  
  14. <span style="white-space:pre">      </span><redisson:cluster-servers slaveConnectionPoolSize="500"   
  15.                                 masterConnectionPoolSize="500"   
  16.                                 idle-connection-timeout="10000"    
  17.                                 connect-timeout="10000"    
  18.                                 timeout="3000"    
  19.                                 ping-timeout="1000"    
  20.                                 reconnection-timeout="3000"    
  21.                                 database="0">    
  22. <span style="white-space:pre">          </span><redisson:node-address value="redis://127.0.0.1:6379" />  
  23. <span style="white-space:pre">          </span><redisson:node-address value="redis://127.0.0.1:6380" />  
  24. <span style="white-space:pre">          </span><redisson:node-address value="redis://127.0.0.1:6381" />  
  25. <span style="white-space:pre">          </span><redisson:node-address value="redis://127.0.0.1:6382" />  
  26. <span style="white-space:pre">          </span><redisson:node-address value="redis://127.0.0.1:6383" />  
  27. <span style="white-space:pre">          </span><redisson:node-address value="redis://127.0.0.1:6384" />  
  28. <span style="white-space:pre">      </span></redisson:cluster-servers>  
  29. <span style="white-space:pre">  </span></redisson:client>  
  30. </beans>  

    SpringRedissonTest.java

 
  1. import org.redisson.api.RBucket;

  2. import org.redisson.api.RedissonClient;

  3. import org.springframework.context.ApplicationContext;

  4. import org.springframework.context.support.ClassPathXmlApplicationContext;

  5. public class SpringRedissonTest {

  6. public static void main(String[] args) {

  7. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring-redisson.xml");

  8. RedissonClient redisson = (RedissonClient) applicationContext.getBean("cluster");

  9. // 首先获取redis中的key-value对象,key不存在没关系

  10. RBucket<String> keyObject = redisson.getBucket("key");

  11. // 如果key存在,就设置key的值为新值value

  12. // 如果key不存在,就设置key的值为value

  13. keyObject.set("value");

  14. }

  15. }

 

    3.4 主从部署方式(master/slave)


    (1)纯java操作

 
  1. //创建配置

  2. Config config = new Config();

  3.  
  4. //指定编码,默认编码为org.redisson.codec.JsonJacksonCodec

  5. //之前使用的spring-data-redis,用的客户端jedis,编码为org.springframework.data.redis.serializer.StringRedisSerializer

  6. //改用redisson后为了之间数据能兼容,这里修改编码为org.redisson.client.codec.StringCodec

  7. config.setCodec(new org.redisson.client.codec.StringCodec());

  8.  
  9. //指定使用主从部署方式

  10. config.useMasterSlaveServers()

  11.     //设置redis主节点

  12.     .setMasterAddress("redis://127.0.0.1:6379")

  13.     //设置redis从节点

  14.     .addSlaveAddress("redis://127.0.0.1:6380", "redis://127.0.0.1:6381");

  15.     

  16. //config.setPassword("password")//设置密码

  17. config.setMasterConnectionPoolSize(500)//设置对于master节点的连接池中连接数最大为500

  18. config.setSlaveConnectionPoolSize(500)//设置对于slave节点的连接池中连接数最大为500

  19. config.setIdleConnectionTimeout(10000)//如果当前连接池里的连接数量超过了最小空闲连接数,而同时有连接空闲时间超过了该数值,那么这些连接将会自动被关闭,并从连接池里去掉。时间单位是毫秒。

  20. config.setConnectTimeout(30000)//同任何节点建立连接时的等待超时。时间单位是毫秒。

  21. config.setTimeout(3000)//等待节点回复命令的时间。该时间从命令发送成功时开始计时。

  22. config.setPingTimeout(30000)

  23. config.setReconnectionTimeout(3000)//当与某个节点的连接断开时,等待与其重新建立连接的时间间隔。时间单位是毫秒。

  24.  
  25. //创建客户端(发现创建RedissonClient非常耗时,基本在2秒-4秒左右)

  26. RedissonClient redisson = Redisson.create(config);

  27.  
  28. //首先获取redis中的key-value对象,key不存在没关系

  29. RBucket<String> keyObject = redisson.getBucket("key");

  30. //如果key存在,就设置key的值为新值value

  31. //如果key不存在,就设置key的值为value

  32. keyObject.set("value");

  33.  
  34. //最后关闭RedissonClient

  35. redisson.shutdown();

    (2)spring集成操作

    pom.xml

[xml] view plain copy

  1. <!--redisson-->  
  2. <dependency>  
  3.     <groupId>org.redisson</groupId>  
  4.     <artifactId>redisson</artifactId>  
  5.     <version>2.10.4</version>  
  6. </dependency>  
  7. <!--spring-->  
  8. <dependency>  
  9.     <groupId>org.springframework</groupId>  
  10.     <artifactId>spring-core</artifactId>  
  11.     <version>4.2.8.RELEASE</version>  
  12. </dependency>  
  13. <dependency>  
  14.     <groupId>org.springframework</groupId>  
  15.     <artifactId>spring-beans</artifactId>  
  16.     <version>4.2.8.RELEASE</version>  
  17. </dependency>  
  18. <dependency>  
  19.     <groupId>org.springframework</groupId>  
  20.     <artifactId>spring-context</artifactId>  
  21.     <version>4.2.8.RELEASE</version>  
  22. </dependency>  

    spring-redisson.xml

[xml] view plain copy

  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2. <span style="white-space:pre">  </span>xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  3. <span style="white-space:pre">  </span>xmlns:context="http://www.springframework.org/schema/context"  
  4. <span style="white-space:pre">  </span>xmlns:redisson="http://redisson.org/schema/redisson"  
  5. <span style="white-space:pre">  </span>xsi:schemaLocation="  
  6.        http://www.springframework.org/schema/beans  
  7.        http://www.springframework.org/schema/beans/spring-beans.xsd  
  8.        http://www.springframework.org/schema/context  
  9.        http://www.springframework.org/schema/context/spring-context.xsd  
  10.        http://redisson.org/schema/redisson  
  11.        http://redisson.org/schema/redisson/redisson.xsd">  
  12.   <bean id="stringCodec" class="org.redisson.client.codec.StringCodec"></bean>    
  13. <span style="white-space:pre">  </span><redisson:client id="masterSlave" codec-ref="stringCodec">  
  14. <span style="white-space:pre">      </span><redisson:master-slave-servers master-address="redis://127.0.0.1:6379"  
  15.                                 slaveConnectionPoolSize="500"    
  16.                                 masterConnectionPoolSize="500"    
  17.                                 idle-connection-timeout="10000"    
  18.                                 connect-timeout="10000"    
  19.                                 timeout="3000"    
  20.                                 ping-timeout="1000"    
  21.                                 reconnection-timeout="3000"    
  22.                                 database="0">  
  23. <span style="white-space:pre">          </span><redisson:slave-address value="redis://127.0.0.1:6380" />  
  24. <span style="white-space:pre">          </span><redisson:slave-address value="redis://127.0.0.1:6381" />  
  25. <span style="white-space:pre">      </span></redisson:master-slave-servers>  
  26. <span style="white-space:pre">  </span></redisson:client>  
  27. </beans>  

    SpringRedissonTest.java

 
  1. import org.redisson.api.RBucket;

  2. import org.redisson.api.RedissonClient;

  3. import org.springframework.context.ApplicationContext;

  4. import org.springframework.context.support.ClassPathXmlApplicationContext;

  5. public class SpringRedissonTest {

  6. public static void main(String[] args) {

  7. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring-redisson.xml");

  8. RedissonClient redisson = (RedissonClient) applicationContext.getBean("masterSlave");

  9. // 首先获取redis中的key-value对象,key不存在没关系

  10. RBucket<String> keyObject = redisson.getBucket("key");

  11. // 如果key存在,就设置key的值为新值value

  12. // 如果key不存在,就设置key的值为value

  13. keyObject.set("value");

  14. }

  15. }

 

    3.5 云托管部署方式

    这种方式主要解决redis提供商为云服务的提供商的redis连接,比如亚马逊云的AWS ElastiCache和微软云的Azure Redis 缓存

    (1)纯java操作

 
  1. Config config = new Config();

  2.  
  3. //指定编码,默认编码为org.redisson.codec.JsonJacksonCodec

  4. //之前使用的spring-data-redis,用的客户端jedis,编码为org.springframework.data.redis.serializer.StringRedisSerializer

  5. //改用redisson后为了之间数据能兼容,这里修改编码为org.redisson.client.codec.StringCodec

  6. config.setCodec(new org.redisson.client.codec.StringCodec());

  7.  
  8. config.useReplicatedServers()

  9. // 主节点变化扫描间隔时间

  10.     .setScanInterval(2000) 

  11.     //设置云服务商的redis服务IP和端口,目前支持亚马逊云的AWS ElastiCache和微软云的Azure Redis 缓存

  12.     .addNodeAddress("redis://123.57.221.104.1:6379")

  13.     .addNodeAddress("redis://123.57.221.105:6380")

  14.     .addNodeAddress("redis://123.57.221.106:6382");

  15.     

  16. //config.setPassword("password")//设置密码

  17. config.setMasterConnectionPoolSize(500)//设置对于master节点的连接池中连接数最大为500

  18. config.setSlaveConnectionPoolSize(500)//设置对于slave节点的连接池中连接数最大为500

  19. config.setIdleConnectionTimeout(10000)//如果当前连接池里的连接数量超过了最小空闲连接数,而同时有连接空闲时间超过了该数值,那么这些连接将会自动被关闭,并从连接池里去掉。时间单位是毫秒。

  20. config.setConnectTimeout(30000)//同任何节点建立连接时的等待超时。时间单位是毫秒。

  21. config.setTimeout(3000)//等待节点回复命令的时间。该时间从命令发送成功时开始计时。

  22. config.setPingTimeout(30000)

  23. config.setReconnectionTimeout(3000)//当与某个节点的连接断开时,等待与其重新建立连接的时间间隔。时间单位是毫秒。

  24.  
  25. //创建客户端(发现创建RedissonClient非常耗时,基本在2秒-4秒左右)

  26. RedissonClient redisson = Redisson.create(config);

  27.  
  28. //首先获取redis中的key-value对象,key不存在没关系

  29. RBucket<String> keyObject = redisson.getBucket("key");

  30. //如果key存在,就设置key的值为新值value

  31. //如果key不存在,就设置key的值为value

  32. keyObject.set("value");

  33.  
  34. //最后关闭RedissonClient

  35. redisson.shutdown();

    (2)spring集成操作

    pom.xml

[xml] view plain copy

  1. <!--redisson-->  
  2. <dependency>  
  3.     <groupId>org.redisson</groupId>  
  4.     <artifactId>redisson</artifactId>  
  5.     <version>2.10.4</version>  
  6. </dependency>  
  7. <!--spring-->  
  8. <dependency>  
  9.     <groupId>org.springframework</groupId>  
  10.     <artifactId>spring-core</artifactId>  
  11.     <version>4.2.8.RELEASE</version>  
  12. </dependency>  
  13. <dependency>  
  14.     <groupId>org.springframework</groupId>  
  15.     <artifactId>spring-beans</artifactId>  
  16.     <version>4.2.8.RELEASE</version>  
  17. </dependency>  
  18. <dependency>  
  19.     <groupId>org.springframework</groupId>  
  20.     <artifactId>spring-context</artifactId>  
  21.     <version>4.2.8.RELEASE</version>  
  22. </dependency>  

    spring-redisson.xml

[xml] view plain copy

  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2. <span style="white-space:pre">  </span>xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  3. <span style="white-space:pre">  </span>xmlns:context="http://www.springframework.org/schema/context"  
  4. <span style="white-space:pre">  </span>xmlns:redisson="http://redisson.org/schema/redisson"  
  5. <span style="white-space:pre">  </span>xsi:schemaLocation="  
  6.        http://www.springframework.org/schema/beans  
  7.        http://www.springframework.org/schema/beans/spring-beans.xsd  
  8.        http://www.springframework.org/schema/context  
  9.        http://www.springframework.org/schema/context/spring-context.xsd  
  10.        http://redisson.org/schema/redisson  
  11.        http://redisson.org/schema/redisson/redisson.xsd">  
  12.   <bean id="stringCodec" class="org.redisson.client.codec.StringCodec"></bean>  
  13. <span style="white-space:pre">  </span><redisson:client id="cloud" codec-ref="stringCodec">  
  14. <span style="white-space:pre">      </span><redisson:replicated-servers slaveConnectionPoolSize="500"    
  15.                                 masterConnectionPoolSize="500"    
  16.                                 idle-connection-timeout="10000"    
  17.                                 connect-timeout="10000"    
  18.                                 timeout="3000"    
  19.                                 ping-timeout="1000"    
  20.                                 reconnection-timeout="3000"    
  21.                                 database="0">>  
  22. <span style="white-space:pre">          </span><redisson:node-address value="redis://123.57.221.104:6379" />  
  23. <span style="white-space:pre">          </span><redisson:node-address value="redis://123.57.221.105:6380" />  
  24. <span style="white-space:pre">          </span><redisson:node-address value="redis://123.57.221.106:6381" />  
  25. <span style="white-space:pre">      </span></redisson:replicated-servers>  
  26. <span style="white-space:pre">  </span></redisson:client>  
  27. </beans>  

    SpringRedissonTest.java

 
  1. import org.redisson.api.RBucket;

  2. import org.redisson.api.RedissonClient;

  3. import org.springframework.context.ApplicationContext;

  4. import org.springframework.context.support.ClassPathXmlApplicationContext;

  5. public class SpringRedissonTest {

  6. public static void main(String[] args) {

  7. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring-redisson.xml");

  8. RedissonClient redisson = (RedissonClient) applicationContext.getBean("cloud");

  9. // 首先获取redis中的key-value对象,key不存在没关系

  10. RBucket<String> keyObject = redisson.getBucket("key");

  11. // 如果key存在,就设置key的值为新值value

  12. // 如果key不存在,就设置key的值为value

  13. keyObject.set("value");

  14. }

  15. }

 

4.Redisson API与原生redis操作命令映射关系

    redisson的客户端API操作和以前的jedis稍微不一样的是你首先得获取到某个操作的key-value对象,然后再对其进行操作,比如我想设置key=time,value=20171013这个string的key-value对象,那么从下表首先查询到SET对应的对象为:
    那么从API操作上你就需要首先获取到RBucket对象,然后调用其3个方法来分别执行set操作,以单节点部署方式举例如下:

 
  1. //创建配置

  2. Config config = new Config();

  3. //指定使用单节点部署方式

  4. config.useSingleServer().setAddress("redis://127.0.0.1:6379");

  5. //创建客户端(发现创建RedissonClient非常耗时,基本在2秒-4秒左右)

  6. RedissonClient redisson = Redisson.create(config);

  7.  
  8. //首先获取redis中的key-value对象,key=time不存在没关系

  9. RBucket<String> keyObject = redisson.getBucket("time");

  10. //如果key=time存在,就设置key=time的值为新值20171013

  11. //如果key=time不存在,就设置key的值为20171013

  12. keyObject.set("20171013");

  13.  
  14. //最后关闭RedissonClient

  15. redisson.shutdown();

    至于其他的redis命令操作通过哪个对象去操作,你可以通过如下表格查询:

Redis命令Redisson对象方法
AUTHConfig.setPassword();
BITCOUNTRBitSet.cardinality(), RBitSet.cardinalityAsync(), RBitSetReactive.cardinality()
BITOPRBitSet.or(), RBitSet.orAsync(), RBitSetReactive.or();
RBitSet.and(), RBitSet.andAsync(), RBitSetReactive.and();
RBitSet.not();
RBitSet.xor(), RBitSet.xorAsync(), RBitSetReactive.xor()
BITPOSRBitSet.length(), RBitSet.lengthAsync(), RBitSetReactive.length()
BLPOPRBlockingQueue.take(), RBlockingQueue.takeAsync(), RBlockingQueueReactive.take();
RBlockingQueue.poll(), RBlockingQueue.pollAsync(), RBlockingQueueReactive.poll();
RBlockingQueue.pollFromAny(), RBlockingQueue.pollFromAnyAsync(), RBlockingQueueReactive.pollFromAny();
BRPOPRBlockingDeque.takeLast(), RBlockingDeque.takeLastAsync(), RBlockingDequeReactive.takeLast();
BRPOPLPUSHRBlockingQueue.pollLastAndOfferFirstTo(), RBlockingQueue.pollLastAndOfferFirstToAsync(), RBlockingQueueReactive.pollLastAndOfferFirstTo();
CLIENT SETNAMEConfig.setClientName();
CLUSTER INFOClusterNode.info();
CLUSTER KEYSLOTRKeys.getSlot(), RKeys.getSlotAsync(), RKeysReactive.getSlot();
CLUSTER NODESUsed in ClusterConnectionManager
DBSIZERKeys.count(), RKeys.countAsync(), RKeysReactive.count();
DECRRAtomicLong.decrementAndGet(), RAtomicLong.decrementAndGetAsync(), RAtomicLongReactive.decrementAndGetAsync();
DELRObject.delete(), RObject.deleteAsync(), RObjectReactive.delete();
RKeys.delete(), RKeys.deleteAsync();
STRLENRBucket.size(), RBucket.sizeAsync(), RBucketReactive.size();
EVALRScript.eval(), RScript.evalAsync(), RScriptReactive.eval();
CLIENT REPLYRBatch.executeSkipResult();
EVALSHARScript.evalSha(), RScript.evalShaAsync(), RScriptReactive.evalSha();
EXISTSRObject.isExists(), RObject.isExistsAsync(), RObjectReactive.isExists();
FLUSHALLRKeys.flushall(), RKeys.flushallAsync(), RKeysReactive.flushall();
FLUSHDBRKeys.flushdb(), RKeys.flushdbAsync(), RKeysReactive.flushdb();
GEOADDRGeo.add(), RGeo.addAsync(), RGeoReactive.add();
GEODISTRGeo.dist(), RGeo.distAsync(), RGeoReactive.dist();
GEOHASHRGeo.hash(), RGeo.hashAsync(), RGeoReactive.hash();
GEOPOSRGeo.pos(), RGeo.posAsync(), RGeoReactive.pos();
GEORADIUSRGeo.radius(), RGeo.radiusAsync(), RGeoReactive.radius();
RGeo.radiusWithDistance(), RGeo.radiusWithDistanceAsync(), RGeoReactive.radiusWithDistance();
RGeo.radiusWithPosition(), RGeo.radiusWithPositionAsync(), RGeoReactive.radiusWithPosition();
GEORADIUSBYMEMBERRGeo.radius(), RGeo.radiusAsync(), RGeoReactive.radius();
RGeo.radiusWithDistance(), RGeo.radiusWithDistanceAsync(), RGeoReactive.radiusWithDistance();
RGeo.radiusWithPosition(), RGeo.radiusWithPositionAsync(), RGeoReactive.radiusWithPosition();
GETRBucket.get(), RBucket.getAsync(), RBucketReactive.get();
GETBITRBitSet.get(), RBitSet.getAsync(), RBitSetReactive.get();
GETSETRBucket.getAndSet(), RBucket.getAndSetAsync(), RBucketReactive.getAndSet();
RAtomicLong.getAndSet(), RAtomicLong.getAndSetAsync(), RAtomicLongReactive.getAndSet();
RAtomicDouble.getAndSet(), RAtomicDouble.getAndSetAsync(), RAtomicDoubleReactive.getAndSet();
HDELRMap.fastRemove(), RMap.fastRemoveAsync(), RMapReactive.fastRemove();
HEXISTSRMap.containsKey(), RMap.containsKeyAsync(), RMapReactive.containsKey();
HGETRMap.get(), RMap.getAsync(), RMapReactive.get();
HSTRLENRMap.valueSize(), RMap.valueSizeAsync(), RMapReactive.valueSize();
HGETALLRMap.readAllEntrySet(), RMap.readAllEntrySetAsync(), RMapReactive.readAllEntrySet();
HINCRBYRMap.addAndGet(), RMap.addAndGetAsync(), RMapReactive.addAndGet();
HINCRBYFLOATRMap.addAndGet(), RMap.addAndGetAsync(), RMapReactive.addAndGet();
HKEYSRMap.readAllKeySet(), RMap.readAllKeySetAsync(), RMapReactive.readAllKeySet();
HLENRMap.size(), RMap.sizeAsync(), RMapReactive.size();
HMGETRMap.getAll(), RMap.getAllAsync(), RMapReactive.getAll();
HMSETRMap.putAll(), RMap.putAllAsync(), RMapReactive.putAll();
HSETRMap.put(), RMap.putAsync(), RMapReactive.put();
HSETNXRMap.fastPutIfAbsent(), RMap.fastPutIfAbsentAsync, RMapReactive.fastPutIfAbsent();
HVALSRMap.readAllValues(), RMap.readAllValuesAsync(), RMapReactive.readAllValues();
INCRRAtomicLong.incrementAndGet(), RAtomicLong.incrementAndGetAsync(), RAtomicLongReactive.incrementAndGet();
INCRBYRAtomicLong.addAndGet(), RAtomicLong.addAndGetAsync(), RAtomicLongReactive.addAndGet();
KEYSRKeys.findKeysByPattern(), RKeys.findKeysByPatternAsync(), RKeysReactive.findKeysByPattern();
RedissonClient.findBuckets();
LINDEXRList.get(), RList.getAsync(), RListReactive.get();
LLENRList.size(), RList.sizeAsync(), RListReactive.Size();
LPOPRQueue.poll(), RQueue.pollAsync(), RQueueReactive.poll();
LPUSHRDeque.addFirst(), RDeque.addFirstAsync();
RDequeReactive.addFirst(), RDeque.offerFirst(), RDeque.offerFirstAsync(), RDequeReactive.offerFirst();
LRANGERList.readAll(), RList.readAllAsync(), RListReactive.readAll();
LREMRList.fastRemove(), RList.fastRemoveAsync(), RList.remove(), RList.removeAsync(), RListReactive.remove();
RDeque.removeFirstOccurrence(), RDeque.removeFirstOccurrenceAsync(), RDequeReactive.removeFirstOccurrence();
RDeque.removeLastOccurrence(), RDeque.removeLastOccurrenceAsync(), RDequeReactive.removeLastOccurrence();
LSETRList.fastSet(), RList.fastSetAsync(), RListReactive.fastSet();
LTRIMRList.trim(), RList.trimAsync(), RListReactive.trim();
LINSERTRList.addBefore(), RList.addBeforeAsync(), RList.addAfter(), RList.addAfterAsync(), RListReactive.addBefore(), RListReactive.addAfter();
MGETRedissonClient.loadBucketValues();
MIGRATERObject.migrate(), RObject.migrateAsync();
MOVERObject.move(), RObject.moveAsync();
MSETRedissonClient.saveBuckets();
PERSISTRExpirable.clearExpire(), RExpirable.clearExpireAsync(), RExpirableReactive.clearExpire();
PEXPIRERExpirable.expire(), RExpirable.expireAsync(), RExpirableReactive.expire();
PEXPIREATRExpirable.expireAt(), RExpirable.expireAtAsync(), RExpirableReactive.expireAt();
PFADDRHyperLogLog.add(), RHyperLogLog.addAsync(), RHyperLogLogReactive.add();
RHyperLogLog.addAll(), RHyperLogLog.addAllAsync(), RHyperLogLogReactive.addAll();
PFCOUNTRHyperLogLog.count(), RHyperLogLog.countAsync(), RHyperLogLogReactive.count();
RHyperLogLog.countWith(), RHyperLogLog.countWithAsync(), RHyperLogLogReactive.countWith();
PFMERGERHyperLogLog.mergeWith(), RHyperLogLog.mergeWithAsync(), RHyperLogLogReactive.mergeWith();
PINGNode.ping(); NodesGroup.pingAll();
PSUBSCRIBERPatternTopic.addListener();
PTTLRExpirable.remainTimeToLive(), RExpirable.remainTimeToLiveAsync(), RExpirableReactive.remainTimeToLive();
PUBLISHRTopic.publish
PUNSUBSCRIBERPatternTopic.removeListener();
RANDOMKEYRKeys.randomKey(), RKeys.randomKeyAsync(), RKeysReactive.randomKey();
RENAMERObject.rename(), RObject.renameAsync(), RObjectReactive.rename();
RENAMENXRObject.renamenx(), RObject.renamenxAsync(), RObjectReactive.renamenx();
RPOPRDeque.pollLast(), RDeque.pollLastAsync(), RDequeReactive.pollLast();
RDeque.removeLast(), RDeque.removeLastAsync(), RDequeReactive.removeLast();
RPOPLPUSHRDeque.pollLastAndOfferFirstTo(), RDeque.pollLastAndOfferFirstToAsync();
RPUSHRList.add(), RList.addAsync(), RListReactive.add();
SADDRSet.add(), RSet.addAsync(), RSetReactive.add();
SCARDRSet.size(), RSet.sizeAsync(), RSetReactive.size();
SCRIPT EXISTSRScript.scriptExists(), RScript.scriptExistsAsync(), RScriptReactive.scriptExists();
SCRIPT FLUSHRScript.scriptFlush(), RScript.scriptFlushAsync(), RScriptReactive.scriptFlush();
SCRIPT KILLRScript.scriptKill(), RScript.scriptKillAsync(), RScriptReactive.scriptKill();
SCRIPT LOADRScript.scriptLoad(), RScript.scriptLoadAsync(), RScriptReactive.scriptLoad();
SDIFFSTORERSet.diff(), RSet.diffAsync(), RSetReactive.diff();
SELECTConfig.setDatabase();
SETRBucket.set(); RBucket.setAsync(); RBucketReactive.set();
SETBITRBitSet.set(); RBitSet.setAsync(); RBitSet.clear(); RBitSet.clearAsync();
SETEXRBucket.set(); RBucket.setAsync(); RBucketReactive.set();
SETNXRBucket.trySet(); RBucket.trySetAsync(); RBucketReactive.trySet();
SISMEMBERRSet.contains(), RSet.containsAsync(), RSetReactive.contains();
SINTERSTORERSet.intersection(), RSet.intersectionAsync(), RSetReactive.intersection();
SINTERRSet.readIntersection(), RSet.readIntersectionAsync(), RSetReactive.readIntersection();
SMEMBERSRSet.readAll(), RSet.readAllAsync(), RSetReactive.readAll();
SMOVERSet.move(), RSet.moveAsync(), RSetReactive.move();
SPOPRSet.removeRandom(), RSet.removeRandomAsync(), RSetReactive.removeRandom();
SREMRSet.remove(), RSet.removeAsync(), RSetReactive.remove();
SUBSCRIBERTopic.addListener(), RTopicReactive.addListener();
SUNIONRSet.readUnion(), RSet.readUnionAsync(), RSetReactive.readUnion();
SUNIONSTORERSet.union(), RSet.unionAsync(), RSetReactive.union();
TTLRExpirable.remainTimeToLive(), RExpirable.remainTimeToLiveAsync(), RExpirableReactive.remainTimeToLive();
UNSUBSCRIBERTopic.removeListener(), RTopicReactive.removeListener();
ZADDRScoredSortedSet.add(), RScoredSortedSet.addAsync(), RScoredSortedSetReactive.add();
ZCARDRScoredSortedSet.size(), RScoredSortedSet.sizeAsync(), RScoredSortedSetReactive.size();
ZINCRBYRScoredSortedSet.addScore(), RScoredSortedSet.addScoreAsync(), RScoredSortedSetReactive.addScore();
ZLEXCOUNTRLexSortedSet.lexCount(), RLexSortedSet.lexCountAsync(), RLexSortedSetReactive.lexCount(); 
RLexSortedSet.lexCountHead(), RLexSortedSet.lexCountHeadAsync(), RLexSortedSetReactive.lexCountHead();
RLexSortedSet.lexCountTail(), RLexSortedSet.lexCountTailAsync(), RLexSortedSetReactive.lexCountTail();
ZRANGERScoredSortedSet.valueRange(), RScoredSortedSet.valueRangeAsync(), RScoredSortedSetReactive.valueRange();
ZREVRANGERScoredSortedSet.valueRangeReversed(), RScoredSortedSet.valueRangeReversedAsync(), RScoredSortedSetReactive.valueRangeReversed();
ZUNIONSTORERScoredSortedSet.union(), RScoredSortedSet.unionAsync(), RScoredSortedSetReactive.union();
ZINTERSTORERScoredSortedSet.intersection(), RScoredSortedSet.intersectionAsync(), RScoredSortedSetReactive.intersection();
ZRANGEBYLEXRLexSortedSet.lexRange(), RLexSortedSet.lexRangeAsync(), RLexSortedSetReactive.lexRange(); 
RLexSortedSet.lexRangeHead(), RLexSortedSet.lexRangeHeadAsync(), RLexSortedSetReactive.lexRangeHead();
RLexSortedSet.lexRangeTail(), RLexSortedSet.lexRangeTailAsync(), RLexSortedSetReactive.lexRangeTail();
ZRANGEBYSCORERScoredSortedSet.valueRange(), RScoredSortedSet.valueRangeAsync(), RScoredSortedSetReactive.valueRange(); 
RScoredSortedSet.entryRange(), RScoredSortedSet.entryRangeAsync(), RScoredSortedSetReactive.entryRange();
TIMENode.time();
ZRANKRScoredSortedSet.rank(), RScoredSortedSet.rankAsync(), RScoredSortedSetReactive.rank();
ZREMRScoredSortedSet.remove(), RScoredSortedSet.removeAsync(), RScoredSortedSetReactive.remove();
RScoredSortedSet.removeAll(), RScoredSortedSet.removeAllAsync(), RScoredSortedSetReactive.removeAll();
ZREMRANGEBYLEXRLexSortedSet.removeRangeByLex(), RLexSortedSet.removeRangeByLexAsync(), RLexSortedSetReactive.removeRangeByLex(); 
RLexSortedSet.removeRangeHeadByLex(), RLexSortedSet.removeRangeHeadByLexAsync(), RLexSortedSetReactive.removeRangeHeadByLex();
RLexSortedSet.removeRangeTailByLex(), RLexSortedSet.removeRangeTailByLexAsync(), RLexSortedSetReactive.removeRangeTailByLex();
ZREMRANGEBYLEXRScoredSortedSet.removeRangeByRank(), RScoredSortedSet.removeRangeByRankAsync(), RScoredSortedSetReactive.removeRangeByRank();
ZREMRANGEBYSCORERScoredSortedSet.removeRangeByScore(), RScoredSortedSet.removeRangeByScoreAsync(), RScoredSortedSetReactive.removeRangeByScore();
ZREVRANGEBYSCORERScoredSortedSet.entryRangeReversed(), RScoredSortedSet.entryRangeReversedAsync(), RScoredSortedSetReactive.entryRangeReversed(), RScoredSortedSet.valueRangeReversed(), RScoredSortedSet.valueRangeReversedAsync(), RScoredSortedSetReactive.valueRangeReversed();
ZREVRANKRScoredSortedSet.revRank(), RScoredSortedSet.revRankAsync(), RScoredSortedSetReactive.revRank();
ZSCORERScoredSortedSet.getScore(), RScoredSortedSet.getScoreAsync(), RScoredSortedSetReactive.getScore();
SCANRKeys.getKeys(), RKeysReactive.getKeys();
SSCANRSet.iterator(), RSetReactive.iterator();
HSCANRMap.keySet().iterator(), RMap.values().iterator(), RMap.entrySet().iterator(), RMapReactive.keyIterator(), RMapReactive.valueIterator(), RMapReactive.entryIterator();
ZSCANRScoredSortedSet.iterator(), RScoredSortedSetReactive.iterator();

 

5.Redisson的同步和异步操作API

    Redisson框架提供的几乎所有对象都包含了同步和异步相互匹配的方法。这些对象都可以通过RedissonClient接口获取。同时还为大部分Redisson对象提供了满足异步流处理标准的程序接口RedissonReactiveClient。

    5.1 同步执行方式

 
  1. // 同步执行方式

  2. RedissonClient client = Redisson.create(config);

  3. RAtomicLong longObject = client.getAtomicLong('myLong');

  4. longObject.compareAndSet(3, 401);

 

    5.2 异步执行方式

 
  1. // 异步执行方式

  2. RedissonClient client = Redisson.create(config);

  3. RAtomicLong longObject = client.getAtomicLong('myLong');

  4. longObject.compareAndSetAsync(3, 401);

 

    5.3 异步流执行方式

 
  1. // 异步流执行方式

  2. RedissonReactiveClient client = Redisson.createReactive(config);

  3. RAtomicLongReactive longObject = client.getAtomicLong('myLong');

  4. longObject.compareAndSet(3, 401);

 

6.redisson支持的配置方式

    6.1 直接操作程序API

        Redisson程序化的配置方法是通过构建Config对象实例来实现的。例如:

 
  1. Config config = new Config();

  2. config.setUseLinuxNativeEpoll(true);

  3. config.useClusterServers()

  4. //可以用"rediss://"来启用SSL连接

  5. .addNodeAddress("redis://127.0.0.1:7181");

 

    6.2 通过JSON文件配置

        Redisson的配置文件可以是JSON格式。 可以通过调用Config.fromJSON方法并指定一个File实例来实现读取JSON格式的配置:

 
  1. Config config = Config.fromJSON(new File("config-file.json"));

  2. RedissonClient redisson = Redisson.create(config);

 

    6.3 通过YAML文件配置

        Redisson的配置文件可以是YAML格式。 可以通过调用config.fromYAML方法并指定一个File实例来实现读取YAML格式的配置:

 
  1. Config config = Config.fromYAML(new File("config-file.yaml"));

  2. RedissonClient redisson = Redisson.create(config);

 

    6.4 通过Spring XML配置

        Redisson为Spring框架提供了一套通过命名空间来配置实例的方式。一个Redisson的实例可以通过这样的方式来配置: 

[xml] view plain copy

  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  3.     xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:redisson="http://redisson.org/schema/redisson"  
  5.     xsi:schemaLocation="  
  6.        http://www.springframework.org/schema/beans  
  7.        http://www.springframework.org/schema/beans/spring-beans.xsd  
  8.        http://www.springframework.org/schema/context  
  9.        http://www.springframework.org/schema/context/spring-context.xsd  
  10.        http://redisson.org/schema/redisson  
  11.        http://redisson.org/schema/redisson/redisson.xsd">  
  12. <!-- 配置分类1:netty相关-->  
  13. <!-- 配置分类2:redis服务端IP和端口-->  
  14. <!-- 配置分类3:redisson客户端负载均衡-->  
  15. <!-- 配置分类4:发布和订阅连接池配置-->  
  16. <!-- 配置分类5:连接池配置-->  
  17. <!-- 配置分类6:超时设置-->  
  18. <!-- 配置分类7:失败重试配置-->  
  19. <!-- 配置分类8:redis库和密码设置-->  
  20. <!-- 配置分类9:SSL相关设置-->  
  21. <!-- 配置分类10:特有的配置 -->  
  22. <redisson:client>  
  23.     <!-- 单节点部署方式  -->  
  24.     <redisson:single-server ... />  
  25.     <!-- 主从部署方式  -->  
  26.     <redisson:master-slave-servers ... />  
  27.     <!-- 哨兵部署方式 -->  
  28.     <redisson:sentinel-servers ... />  
  29.     <!-- 集群部署方式 -->  
  30.     <redisson:cluster-servers ... />  
  31.     <!-- 云部署方式 -->  
  32.     <redisson:replicated-servers ... />  
  33. </redisson:client>  
  34. </beans>  

 

    更多的使用方法请前往第三方框架整合文档了解。 举例单节点redis的详细配置如下:

[xml] view plain copy

  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.        xmlns:context="http://www.springframework.org/schema/context"  
  4.        xmlns:redisson="http://redisson.org/schema/redisson"  
  5.        xsi:schemaLocation="  
  6.        http://www.springframework.org/schema/beans  
  7.        http://www.springframework.org/schema/beans/spring-beans.xsd  
  8.        http://www.springframework.org/schema/context  
  9.        http://www.springframework.org/schema/context/spring-context.xsd  
  10.        http://redisson.org/schema/redisson  
  11.        http://redisson.org/schema/redisson/redisson.xsd">  
  12.          
  13.     <!-- 单Redis节点模式的配置 -->  
  14.     <bean id="jsonJacksonCodec" class="org.redisson.codec.JsonJacksonCodec"></bean>  
  15.     <bean id="defaultCodecProvider" class="org.redisson.codec.DefaultCodecProvider"></bean>  
  16.     <bean id="defaultResolverProvider" class="org.redisson.liveobject.provider.DefaultResolverProvider"></bean>  
  17.     <bean id="nioEventLoopGroup" class="io.netty.channel.nio.NioEventLoopGroup"></bean>  
  18.       
  19.     <bean id="defaultThreadFactory" class="io.netty.util.concurrent.DefaultThreadFactory">  
  20.         <constructor-arg name="poolName" value="redisson"></constructor-arg>  
  21.     </bean>  
  22.     <bean id="executors" factory-method="newFixedThreadPool" class="java.util.concurrent.Executors">  
  23.         <constructor-arg name="nThreads" value="50"></constructor-arg>  
  24.         <constructor-arg ref="defaultThreadFactory"></constructor-arg>  
  25.     </bean>  
  26.       
  27.     <redisson:client   
  28.         id="standalone"  
  29.         name="aliasName1,aliasName2"   
  30.         threads="8"   
  31.         netty-threads="8"   
  32.         codec-ref="jsonJacksonCodec"  
  33.         codec-provider-ref="defaultCodecProvider"   
  34.         use-linux-native-epoll="false"  
  35.         redisson-reference-enabled="true"  
  36.         resolver-provider-ref="defaultResolverProvider"   
  37.         executor-ref="executors"   
  38.         event-loop-group-ref="nioEventLoopGroup" >  
  39.     <redisson:single-server   
  40.         address="redis://192.168.29.24:6379"     
  41.         subscription-connection-minimum-idle-size="1"  
  42.         subscriptions-per-connection="50"  
  43.         subscription-connection-pool-size="50"  
  44.         connection-minimum-idle-size="10"  
  45.         connection-pool-size="64"  
  46.         idle-connection-timeout="10000"  
  47.         connect-timeout="10000"  
  48.         timeout="3000"  
  49.         ping-timeout="3000"  
  50.         retry-attempts="3"  
  51.         retry-interval="1500"  
  52.         reconnection-timeout="3000"  
  53.         failed-attempts="3"  
  54.         database="0"  
  55.         password=""  
  56.         client-name=""  
  57.         ssl-enable-endpoint-identification="true"  
  58.         ssl-keystore=""  
  59.         ssl-keystore-password=""  
  60.         ssl-provider="JDK"  
  61.         ssl-truststore=""  
  62.         ssl-truststore-password=""  
  63.         dns-monitoring="false"  
  64.         dns-monitoring-interval="5000"/>  
  65.     </redisson:client>  
  66. </beans>  

 

 

7.redisson如何配置参数

    redisson的配置参数很多,容易让人感觉疲乏,更恐怖的是针对每种部署方式,相关参数也不尽相同,但不管怎么变化,配置参数的归类就那么几个,初学者可以先记住配置参数的大致分类,然后针对每个分类下的不同参数有无进行对比总结,这样能方便理解,总结归类redisson的配置参数分类如下:

  • 配置分类1:netty相关
  • 配置分类2:redis服务端IP和端口
  • 配置分类3:redisson客户端负载均衡
  • 配置分类4:发布和订阅连接池配置
  • 配置分类5:连接池配置
  • 配置分类6:超时设置
  • 配置分类7:失败重试配置
  • 配置分类8:redis库和密码设置
  • 配置分类9:SSL相关设置
  • 配置分类10:特有的配置

    前面已经知道如何简单的去操作redisson客户端来调用redis服务端,默认值设置了服务端相关的redis IP地址和端口,没有做过多设置,那么redisson有哪些方面设置,如何设置呢?

  •     因为redisson是基于java的网络编程框架netty实现,所以首先提供了暴露了netty相关配置参数;
  •     redis服务端要么是单机要么是多机,那么这里必然存在主从相关设置;
  •     redisson作为客户端,如果频繁去创建和关闭连接,那么性能必然大幅下降,那么这里必然有连接池相关配置;
  •     考虑到安全相关,所以redis还需要有SSL相关设置;
  •     后面还有客户端操作失败重试相关设置参数和根据不同部署的特殊配置;

    这里将各种部署方式的配置列表如下:

配置分类配置介绍

netty相关

 

 

    以下参数主要影响redisson里面的netty网络编程框架,如果想了解更多建议去实际使用以下netty框架,在redisson里在常用配置参数环节有介绍:
配置参数配置介绍单节点主从哨兵集群云托管
codec默认值: org.redisson.codec.JsonJacksonCodec
threads默认值: 当前处理核数量 * 2,这个线程池数量被所有RTopic对象监听器,RRemoteService调用者和RExecutorService任务共同共享。
nettyThreads默认值: 当前处理核数量 * 2,这个线程池数量是在一个Redisson实例内,被其创建的所有分布式数据类型和服务,以及底层客户端所一同共享的线程池里保存的线程数量。
executor单独提供一个用来执行所有RTopic对象监听器,RRemoteService调用者和RExecutorService任务的线程池(ExecutorService)实例。
eventLoopGroup用于特别指定一个EventLoopGroup. EventLoopGroup是用来处理所有通过Netty与Redis服务之间的连接发送和接受的消息。每一个Redisson都会在默认情况下自己创建管理一个EventLoopGroup实例。因此,如果在同一个JVM里面可能存在多个Redisson实例的情况下,采取这个配置实现多个Redisson实例共享一个EventLoopGroup的目的。只有io.netty.channel.epoll.EpollEventLoopGroup或io.netty.channel.nio.NioEventLoopGroup才是允许的类型。
useLinuxNativeEpoll默认值: false,如果服务器的绑定地址是本地回路网络接口(loopback interface)则自动激活一个UNIX域套接字。并同时采用epoll作为传输方式。请自行添加 netty-transport-native-epoll 依赖库。
 redis服务端IP和端口 
配置参数配置介绍单节点主从哨兵集群云托管
address通过host:port的格式来指定节点地址。    
masterAddress通过host:port的格式来指定主节点地址。    
addSlaveAddress通过host:port的格式来指定从节点的地址。多个节点可以一次性批量添加。    
addSentinelAddress通过host:port的格式来指定哨兵节点的地址。多个节点可以一次性批量添加。    
addNodeAddress通过host:port的格式来添加Redis集群节点的地址。多个节点可以一次性批量添加。    
nodeAddresses通过host:port的格式来指定云托管模式的多个Redis集群节点的地址。多个节点可以一次性批量添加。所有的主从节点必须在配置阶段全部体现出来。    
 redisson客户端负载均衡 
配置参数配置介绍单节点主从哨兵集群云托管
scanInterval对主节点变化节点状态扫描的时间间隔。单位是毫秒。   
readMode默认值: SLAVE(只在从服务节点里读取)

注:在从服务节点里读取的数据说明已经至少有两个节点保存了该数据,确保了数据的高可用性。

设置读取操作选择节点的模式。 可用值为: SLAVE - 只在从服务节点里读取。 MASTER - 只在主服务节点里读取。 MASTER_SLAVE - 在主从服务节点里都可以读取。
 
subscriptionMode  
loadBalancer默认值: org.redisson.connection.balancer.RoundRobinLoadBalancer

在使用多个Elasticache Redis服务节点的环境里,可以选用以下几种负载均衡方式选择一个节点: org.redisson.connection.balancer.WeightedRoundRobinBalancer - 权重轮询调度算法 org.redisson.connection.balancer.RoundRobinLoadBalancer - 轮询调度算法 org.redisson.connection.balancer.RandomLoadBalancer - 随机调度算法
 
 发布和订阅连接池配置 
配置参数配置介绍单节点主从哨兵集群云托管
subscriptionConnectionMinimumIdleSize默认值:1

用于发布和订阅连接的最小保持连接数(长连接)。Redisson内部经常通过发布和订阅来实现许多功能。长期保持一定数量的发布订阅连接是必须的。
subscriptionsPerConnection默认值:50

用于发布和订阅连接的连接池最大容量。连接池的连接数量自动弹性伸缩。
subscriptionConnectionPoolSize默认值:50

多从节点的环境里,每个 从服务节点里用于发布和订阅连接的连接池最大容量。连接池的连接数量自动弹性伸缩。
连接池配置
配置参数配置介绍单节点主从哨兵集群云托管
slaveConnectionMinimumIdleSize默认值:10

多从节点的环境里,每个 从服务节点里用于普通操作(非 发布和订阅)的最小保持连接数(长连接)。长期保持一定数量的连接有利于提高瞬时读取反映速度。
 
slaveConnectionPoolSize默认值:64

多从节点的环境里,每个 从服务节点里用于普通操作(非 发布和订阅)连接的连接池最大容量。连接池的连接数量自动弹性伸缩。
 
connectionMinimumIdleSize默认值:10

最小保持连接数(长连接)。长期保持一定数量的连接有利于提高瞬时写入反应速度。
    
connectionPoolSize默认值:64

连接池最大容量。连接池的连接数量自动弹性伸缩。
    
masterConnectionMinimumIdleSizemasterConnectionMinimumIdleSize(主节点最小空闲连接数)

默认值:10

多从节点的环境里,每个 主节点的最小保持连接数(长连接)。长期保持一定数量的连接有利于提高瞬时写入反应速度。
 
masterConnectionPoolSize默认值:64

主节点的连接池最大容量。连接池的连接数量自动弹性伸缩。
 
idleConnectionTimeout默认值:10000

如果当前连接池里的连接数量超过了最小空闲连接数,而同时有连接空闲时间超过了该数值,那么这些连接将会自动被关闭,并从连接池里去掉。时间单位是毫秒。
 超时设置 
配置参数配置介绍单节点主从哨兵集群云托管
connectTimeout默认值:10000

同节点建立连接时的等待超时。时间单位是毫秒。
timeout默认值:3000

等待节点回复命令的时间。该时间从命令发送成功时开始计时。
 失败重试配置 
配置参数配置介绍单节点主从哨兵集群云托管
retryAttempts默认值:3

如果尝试达到 retryAttempts(命令失败重试次数) 仍然不能将命令发送至某个指定的节点时,将抛出错误。如果尝试在此限制之内发送成功,则开始启用 timeout(命令等待超时) 计时。
retryInterval默认值:1500

在一条命令发送失败以后,等待重试发送的时间间隔。时间单位是毫秒。
reconnectionTimeout默认值:3000

当与某个节点的连接断开时,等待与其重新建立连接的时间间隔。时间单位是毫秒。
failedAttempts默认值:3

在某个节点执行相同或不同命令时,连续 失败 failedAttempts(执行失败最大次数) 时,该节点将被从可用节点列表里清除,直到 reconnectionTimeout(重新连接时间间隔) 超时以后再次尝试。
redis库和密码设置
配置参数配置介绍单节点主从哨兵集群云托管
database默认值:0

尝试连接的数据库编号。
password默认值:null

用于节点身份验证的密码。
clientName默认值:null

在Redis节点里显示的客户端名称。
SSL相关设置
配置参数配置介绍单节点主从哨兵集群云托管
sslEnableEndpointIdentification默认值:true

开启SSL终端识别能力。
sslProvider默认值:JDK

确定采用哪种方式(JDK或OPENSSL)来实现SSL连接。
sslTruststore默认值:null

指定SSL信任证书库的路径。
sslTruststorePassword默认值:null

指定SSL信任证书库的密码。
sslKeystore默认值:null

指定SSL钥匙库的路径。
sslKeystorePassword默认值:null

指定SSL钥匙库的密码。
特有的配置
配置参数配置介绍单节点主从哨兵集群云托管
dnsMonitoring默认值:false

在启用该功能以后,Redisson将会监测DNS的变化情况。
    
dnsMonitoringInterval默认值:5000

监测DNS的变化情况的时间间隔。
    
masterName主服务器的名称是哨兵进程中用来监测主从服务切换情况的。    

 

8. 单个集合数据分片(有Redisson PRO版本限制)

    目前支持的数据结构类型包括Set和Map.该功能仅限于Redisson PRO版本

    参见https://github.com/redisson/redisson/wiki

 

9.分布式对象

    包含通用对象桶(Object Bucket)、二进制流(Binary Stream)、地理空间对象桶(Geospatial Bucket)、BitSet、原子整长形(AtomicLong)、原子双精度浮点数(AtomicDouble)、话题(订阅分发)、模糊话题、布隆过滤器(Bloom Filter)、基数估计算法(HyperLogLog)。

    参见https://github.com/redisson/redisson/wiki

 

10.分布式集合(有Redisson PRO版本限制)

    包含映射(Map)、映射(Map)、多值映射(Multimap)、集(Set)、有序集(SortedSet)、计分排序集(ScoredSortedSet)、字典排序集(LexSortedSet)、列表(List)、列队(Queue)、双端队列(Deque)、阻塞队列(Blocking Queue)、有界阻塞列队(Bounded Blocking Queue)、阻塞双端列队(Blocking Deque)、阻塞公平列队(Blocking Fair Queue)、延迟列队(Delayed Queue)、优先队列(Priority Queue)、优先双端队列(Priority Deque)。

    其中映射(Map)和集(Set)功能仅限于Redisson PRO版本

    参见https://github.com/redisson/redisson/wiki

 

11.分布式锁(Lock)和同步器(Synchronizer)

    包含可重入锁(Reentrant Lock)公平锁(Fair Lock)联锁(MultiLock)红锁(RedLock)读写锁(ReadWriteLock)信号量(Semaphore)可过期性信号量(PermitExpirableSemaphore)闭锁(CountDownLatch)。

    参见https://github.com/redisson/redisson/wiki

 

12.分布式服务

    包含分布式远程服务(Remote Service)、分布式实时对象(Live Object)服务、分布式执行服务(Executor Service)、分布式调度任务服务(Scheduler Service)、分布式映射归纳服务(MapReduce)。

    参见https://github.com/redisson/redisson/wiki

 

13.额外功能

    包含对Redis节点的操作、复杂多维对象结构和对象引用的支持、命令的批量执行、脚本执行、底层Redis客户端。

    参见https://github.com/redisson/redisson/wiki

 

14.独立节点模式



 

    Redisson Node指的是Redisson在分布式运算环境中作为独立节点运行的一种模式。Redisson Node的功能可以用来执行通过分布式执行服务分布式调度执行服务发送的远程任务,也可以用来为分布式远程服务提供远端服务。 所有这些功能全部包含在一个JAR包里,您可以从这里下载.。

    参见https://github.com/redisson/redisson/wiki

 

15.工具(有Redisson PRO版本限制)

 

    包含Redis部署工具、集群管理工具。

    其中Redis部署工具和集群管理工具功能仅限于Redisson PRO版本

    参见https://github.com/redisson/redisson/wiki

 

16.第三方框架整合

    包含Spring框架整合、Spring Cache整合、Hibernate整合、Java缓存标准规范JCache API (JSR-107)、Tomcat会话管理器(Tomcat Session Manager)、Spring Session会话管理器。

    参见https://github.com/redisson/redisson/wiki

 

17.问题记录

    17.1 maven jar冲突问题

        redisson本身依赖一些第三方jar,比如netty,如果在项目中其他maven依赖已经存在这些jar,那么可能导致redisson假死或者卡死现象,比如hbase就依赖netty,如果hbase和redisson同时在项目中出现,并且hbase的maven配置在redisson之前,那么hbase依赖的netty会生效,这样redisson依赖的netty会被抛弃,解决的办法是设置hbase不要依赖netty,设置如下:

[xml] view plain copy

  1. <!-- hbase -->  
  2. <dependency>  
  3.     <groupId>org.apache.hbase</groupId>  
  4.     <artifactId>hbase-client</artifactId>  
  5.     <version>1.2.1</version>  
  6.     <exclusions>  
  7.         <exclusion>  
  8.             <artifactId>netty-all</artifactId>  
  9.             <groupId>io.netty</groupId>  
  10.         </exclusion>  
  11.         <exclusion>  
  12.             <artifactId>netty</artifactId>  
  13.             <groupId>io.netty</groupId>  
  14.         </exclusion>  
  15.     </exclusions>  
  16. </dependency>  
  17.   
  18. <!-- redisson -->  
  19. <!-- JDK 1.8+ compatible -->  
  20. <!--           
  21. <dependency>  
  22.     <groupId>org.redisson</groupId>  
  23.     <artifactId>redisson</artifactId>  
  24.     <version>3.5.4</version>  
  25. </dependency> -->  
  26. <!-- JDK 1.6+ compatible -->  
  27. <dependency>  
  28.     <groupId>org.redisson</groupId>  
  29.     <artifactId>redisson</artifactId>  
  30.     <version>2.10.4</version>  
  31. </dependency>  

    redisson的依赖jar如下:

Group idArtifact IdVersionDependency
io.nettynetty-common4.1+required
io.nettynetty-codec4.1+required
io.nettynetty-buffer4.1+required
io.nettynetty-transport4.1+required
io.nettynetty-handler4.1+required
net.openhftzero-allocation-hashing0.8+required
com.fasterxml.jackson.dataformatjackson-core2.7+required
com.fasterxml.jackson.dataformatjackson-databind2.7+required
com.fasterxml.jackson.dataformatjackson-databind2.7+required
com.fasterxml.jackson.dataformatjackson-dataformat-yaml2.7+optional (used for yaml configuration)
net.bytebuddybyte-buddy1.6+optional (used for LiveObject service)
org.joddjodd-bean3.7+optional (used for LiveObject service)
javax.cachecache-api1.0.0optional (used for JCache implementation)
io.projectreactorreactor-stream2.0.8optional (used for RedissonReactiveClient)

 

    17.2 redisson操作完后客户端一直处于运行状态,类似于后台进程一直运行

        这个主要是因为redisson使用netty将redis引入java后,本身就是一个常驻后台执行的程序,如果要强制关闭,请加上以下代码即可:

redisson.shutdown();
  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Spring Boot整合RedisRedisson可以让我们更方便地使用Redis作为缓存或分布式锁。下面是一个简单的示例,展示了如何在Spring Boot项目中实现这个整合: 1. 首先,在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.redisson</groupId> <artifactId>redisson-spring-boot-starter</artifactId> <version>3.16.0</version> </dependency> ``` 2. 在application.properties或application.yml中配置Redis连接信息: ```properties spring.redis.host=127.0.0.1 spring.redis.port=6379 ``` 3. 在你的Spring Boot配置类中添加Redisson的配置: ```java @Configuration public class RedissonConfig { @Bean public RedissonClient redissonClient() { Config config = new Config(); config.useSingleServer() .setAddress("redis://127.0.0.1:6379"); return Redisson.create(config); } } ``` 4. 在你的业务代码中使用RedisRedisson: ```java @Service public class MyService { @Autowired private RedisTemplate<String, Object> redisTemplate; @Autowired private RedissonClient redissonClient; public void put(String key, Object value) { // 使用RedisTemplate操作Redis redisTemplate.opsForValue().set(key, value); // 使用Redisson操作Redis RMap<String, Object> map = redissonClient.getMap("myMap"); map.put(key, value); } public Object get(String key) { // 使用RedisTemplate操作Redis return redisTemplate.opsForValue().get(key); // 使用Redisson操作Redis RMap<String, Object> map = redissonClient.getMap("myMap"); return map.get(key); } } ``` 通过上述步骤,你就成功地将RedisRedisson整合到了你的Spring Boot项目中。可以使用`redisTemplate`来直接操作Redis,也可以使用`redissonClient`来获得更多Redisson提供的功能,例如分布式锁、分布式集合等。希望对你有帮助!如果还有其他问题,请继续提问。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值