SpringBoot整合连接Redis集群

灰太狼 2022-11-30 04:27 301阅读 0赞

第一步,新建项目maven项目,添加依赖

(1)本文所采用的SpringBoot的版本如下

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.0.2.RELEASE</version>
  5. <relativePath /> <!-- lookup parent from repository -->
  6. </parent>

(2)加入Redis相关依赖

复制代码

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>redis.clients</groupId>
  7. <artifactId>jedis</artifactId>
  8. </dependency>

复制代码

第二步,application.yml加入redis相关配置

复制代码

  1. spring:
  2. application:
  3. name: redis-cluster
  4. redis:
  5. cluster:
  6. nodes: 192.168.0.102:6379,192.168.0.103:6379,192.168.0.105:6379
  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 #密码
  19. server:
  20. port: 8080

复制代码

第三步,编写配置类

复制代码

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

复制代码

第四步,编写Controller测试类

复制代码

  1. package com.qxj.application;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.data.redis.core.RedisTemplate;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. @RestController
  7. public class TestController {
  8. @Autowired
  9. private RedisTemplate<String, Object> template;
  10. @RequestMapping("/test")
  11. public String test() {
  12. template.opsForValue().set("demo", "hello world! 你好,世界");
  13. String str = (String) template.opsForValue().get("demo");
  14. return str;
  15. }
  16. }

参考文献:https://blog.csdn.net/WYA1993/article/details/88046628

https://www.cnblogs.com/wps54213/p/12608777.html

在springboot使用搭建好的redis集群——lettuce方式

添加redis和连接池依赖

  1. <!--redis连接池 start-->
  2. <dependency>
  3. <groupId>org.apache.commons</groupId>
  4. <artifactId>commons-pool2</artifactId>
  5. </dependency>
  6. <!--redis连接池 end-->
  7. <!--redis start-->
  8. <dependency>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter-data-redis</artifactId>
  11. <version>2.2.6.RELEASE</version>
  12. </dependency>
  13. <!--redis end-->

在配置文件中配置连接池和sentinel

  1. ip: 39.97.234.52
  2. spring:
  3. redis:
  4. lettuce:
  5. pool:
  6. max-active: 10
  7. max-idle: 8
  8. max-wait: -1ms
  9. min-idle: 0
  10. sentinel:
  11. master: mymaster
  12. nodes: ${ip}:26379,${ip}:26380,${ip}:26381
  13. password: test@dbuser2018

添加redis配置类,修改springboot默认的redis序列化方式

  1. @Configuration
  2. public class RedisConfig {
  3. /**
  4. * 把任何数据保存到redis时,都需要进行序列化,默认使用JdkSerializationRedisSerializer进行序列化。
  5. * 默认的序列化会给所有的key,value的原始字符前,都加了一串字符(例如:\xAC\xED\x00\),不具备可读性
  6. * 所以需要配置jackson序列化方式
  7. */
  8. @Bean
  9. public RedisTemplate<String,Object> redisTemplate(LettuceConnectionFactory factory){
  10. RedisTemplate<String,Object> template=new RedisTemplate<>();
  11. template.setConnectionFactory(factory);
  12. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
  13. ObjectMapper objectMapper = new ObjectMapper();
  14. objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  15. objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  16. jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
  17. StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
  18. //key采用String的序列化方式
  19. template.setKeySerializer(stringRedisSerializer);
  20. //value采用jackson序列化方式
  21. template.setValueSerializer(jackson2JsonRedisSerializer);
  22. //hash的key采用String的序列化方式
  23. template.setHashKeySerializer(stringRedisSerializer);
  24. //hash的value采用String的序列化方式
  25. template.setHashValueSerializer(jackson2JsonRedisSerializer);
  26. template.afterPropertiesSet();
  27. return template;
  28. }
  29. }

创建redis服务

  1. @Service
  2. public class RedisServiceImpl implements RedisService {
  3. @Autowired
  4. private RedisTemplate redisTemplate;
  5. @Override
  6. public boolean put(String key, Object value, long seconds) throws JsonProcessingException {
  7. redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
  8. return true;
  9. }
  10. @Override
  11. public <T> T get(String key, Class<T> clazz) throws IOException {
  12. Object o = redisTemplate.opsForValue().get(key);
  13. if (o != null) {
  14. String json = String.valueOf(o);
  15. T t = JsonUtil.stringToObject(json, clazz);
  16. return t;
  17. }
  18. return null;
  19. }
  20. }

创建redisController测试redis服务

  1. @RestController
  2. public class RedisController {
  3. @Autowired
  4. private RedisService redisService;
  5. @PostMapping(value = "put")
  6. public String put(String key,String value,long seconds){
  7. redisService.put(key,value,seconds);
  8. return "ok";
  9. }
  10. @GetMapping(value = "get")
  11. public Object get(String key){
  12. Object o=redisService.get(key);
  13. if(o!=null){
  14. return String.valueOf(o);
  15. }
  16. return "not_ok";
  17. }
  18. }

发表评论

表情:
评论列表 (有 0 条评论,301人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SpringBoot整合redis

    一:缓存的应用场景 1:什么是缓存? 在互联网场景下,尤其 2C 端大流量场景下,需要将一些经常展现和不会频繁变更的数据,存放在存取速率更快的地方。缓存就是一个存储器,在技

    相关 springboot整合redis

    一、redis集群原理 redis集群中的所有节点彼此互联,节点内部采用二进制协议优化传输速度和带宽,每个节点都可以与Java客户端连接。redis集群的数据分配采用哈希