依赖

  1. <dependency>
  2. <groupId>org.projectlombok</groupId>
  3. <artifactId>lombok</artifactId>
  4. <version>1.18.12</version>
  5. </dependency>
  6. <!--redis 客户端-->
  7. <dependency>
  8. <groupId>redis.clients</groupId>
  9. <artifactId>jedis</artifactId>
  10. </dependency>
  11. <!--自定义序列化-->
  12. <dependency>
  13. <groupId>com.fasterxml.jackson.core</groupId>
  14. <artifactId>jackson-databind</artifactId>
  15. </dependency>
  16. <!--属性配置支持-->
  17. <dependency>
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-configuration-processor</artifactId>
  20. <optional>true</optional>
  21. </dependency>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-data-redis</artifactId>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-test</artifactId>
  29. <scope>test</scope>
  30. <exclusions>
  31. <exclusion>
  32. <groupId>org.junit.vintage</groupId>
  33. <artifactId>junit-vintage-engine</artifactId>
  34. </exclusion>
  35. </exclusions>
  36. </dependency>
  37. <dependency>
  38. <groupId>junit</groupId>
  39. <artifactId>junit</artifactId>
  40. <version>4.12</version>
  41. <scope>test</scope>
  42. </dependency>

application.yml

  1. spring:
  2. application:
  3. name: spring-boot-redis-cluster
  4. redis:
  5. cluster:
  6. nodes: *:7001,*:7002,*:7003,*:7004,*:7005,*:7006
  7. max-redirects: 6
  8. redis:
  9. timeout: 10000 #客户端超时时间单位是毫秒 默认是2000
  10. maxIdle: 300 #最大空闲数
  11. maxTotal: 1000 #控制一个pool可分配多少个jedis实例,用来替换上面的redis.maxActive,如果是jedis 2.4以后用该属性
  12. maxWaitMillis: 1000 #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
  13. minEvictableIdleTimeMillis: 300000 #连接的最小空闲时间 默认1800000毫秒(30分钟)
  14. numTestsPerEvictionRun: 1024 #每次释放连接的最大数目,默认3
  15. timeBetweenEvictionRunsMillis: 30000 #逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
  16. testOnBorrow: true #是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
  17. testWhileIdle: true #在空闲时检查有效性, 默认false
  18. password: 123456 #密码

RedisCluster配置类

  1. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  2. import com.fasterxml.jackson.annotation.PropertyAccessor;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import lombok.Data;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.data.redis.connection.RedisClusterConfiguration;
  9. import org.springframework.data.redis.connection.RedisNode;
  10. import org.springframework.data.redis.connection.RedisPassword;
  11. import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
  12. import org.springframework.data.redis.core.RedisTemplate;
  13. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  14. import org.springframework.data.redis.serializer.StringRedisSerializer;
  15. import redis.clients.jedis.JedisPoolConfig;
  16. import java.util.HashSet;
  17. import java.util.Set;
  18. /**
  19. * @author liuhui
  20. * @title: RedisConfig
  21. * @projectName study
  22. * @description: redis 配置类
  23. * @date 2021/4/2811:29
  24. */
  25. @Configuration
  26. @Data
  27. public class RedisClusterConfig {
  28. @Value("${spring.redis.cluster.nodes}")
  29. private String clusterNodes;
  30. @Value("${spring.redis.cluster.max-redirects}")
  31. private int maxRedirects;
  32. @Value("${redis.password}")
  33. private String password;
  34. @Value("${redis.timeout}")
  35. private int timeout;
  36. @Value("${redis.maxIdle}")
  37. private int maxIdle;
  38. @Value("${redis.maxTotal}")
  39. private int maxTotal;
  40. @Value("${redis.maxWaitMillis}")
  41. private int maxWaitMillis;
  42. @Value("${redis.minEvictableIdleTimeMillis}")
  43. private int minEvictableIdleTimeMillis;
  44. @Value("${redis.numTestsPerEvictionRun}")
  45. private int numTestsPerEvictionRun;
  46. @Value("${redis.timeBetweenEvictionRunsMillis}")
  47. private int timeBetweenEvictionRunsMillis;
  48. @Value("${redis.testOnBorrow}")
  49. private boolean testOnBorrow;
  50. @Value("${redis.testWhileIdle}")
  51. private boolean testWhileIdle;
  52. /**
  53. * Redis连接池的配置
  54. *
  55. * @return JedisPoolConfig
  56. */
  57. @Bean
  58. public JedisPoolConfig getJedisPoolConfig() {
  59. JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
  60. // 最大空闲数
  61. jedisPoolConfig.setMaxIdle(maxIdle);
  62. // 连接池的最大数据库连接数
  63. jedisPoolConfig.setMaxTotal(maxTotal);
  64. // 最大建立连接等待时间
  65. jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
  66. // 逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
  67. jedisPoolConfig.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
  68. // 每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3
  69. jedisPoolConfig.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
  70. // 逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
  71. jedisPoolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
  72. // 是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
  73. jedisPoolConfig.setTestOnBorrow(testOnBorrow);
  74. // 在空闲时检查有效性, 默认false
  75. jedisPoolConfig.setTestWhileIdle(testWhileIdle);
  76. return jedisPoolConfig;
  77. }
  78. /**
  79. * Redis集群的配置
  80. *
  81. * @return RedisClusterConfiguration
  82. */
  83. @Bean
  84. public RedisClusterConfiguration redisClusterConfiguration() {
  85. RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
  86. // Set<RedisNode> clusterNodes
  87. System.out.println(clusterNodes);
  88. String[] serverArray = clusterNodes.split(",");
  89. Set<RedisNode> nodes = new HashSet<RedisNode>();
  90. for (String ipPort : serverArray) {
  91. String[] ipAndPort = ipPort.split(":");
  92. nodes.add(new RedisNode(ipAndPort[0].trim(), Integer.valueOf(ipAndPort[1])));
  93. }
  94. redisClusterConfiguration.setClusterNodes(nodes);
  95. redisClusterConfiguration.setMaxRedirects(maxRedirects);
  96. redisClusterConfiguration.setPassword(RedisPassword.of(password));
  97. return redisClusterConfiguration;
  98. }
  99. /**
  100. * redis连接工厂类
  101. *
  102. * @return JedisConnectionFactory
  103. */
  104. @Bean
  105. public JedisConnectionFactory jedisConnectionFactory() {
  106. // 集群模式
  107. JedisConnectionFactory factory = new JedisConnectionFactory(redisClusterConfiguration(), getJedisPoolConfig());
  108. return factory;
  109. }
  110. /**
  111. * 实例化 RedisTemplate 对象
  112. *
  113. * @return RedisTemplate<String, Object>
  114. */
  115. @Bean
  116. public RedisTemplate<String, Object> redisTemplate() {
  117. RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
  118. // Template初始化
  119. initDomainRedisTemplate(redisTemplate);
  120. return redisTemplate;
  121. }
  122. /**
  123. * 设置数据存入 redis 的序列化方式 使用默认的序列化会导致key乱码
  124. */
  125. private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
  126. // 开启redis数据库事务的支持
  127. redisTemplate.setEnableTransactionSupport(true);
  128. redisTemplate.setConnectionFactory(jedisConnectionFactory());
  129. // 如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to
  130. // String!
  131. StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
  132. redisTemplate.setKeySerializer(stringRedisSerializer);
  133. // hash的key也采用String的序列化方式
  134. redisTemplate.setHashKeySerializer(stringRedisSerializer);
  135. // jackson序列化对象设置
  136. Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(
  137. Object.class);
  138. ObjectMapper om = new ObjectMapper();
  139. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  140. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  141. jackson2JsonRedisSerializer.setObjectMapper(om);
  142. // value序列化方式采用jackson
  143. redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
  144. // hash的value序列化方式采用jackson
  145. redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
  146. redisTemplate.afterPropertiesSet();
  147. }
  148. }