redis学习系列(二)--spring boot整合Redis集群

偏执的太偏执、 2022-06-01 07:43 245阅读 0赞

spring boot整合Redis集群

开发

项目地址 https://gitee.com/zhenhai_zheng/springboot_rediscluster.git

添加依赖,加载Jedis

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>

添加redis配置

springboot配置文件中添加集群的信息

  1. # Redis服务器地址
  2. #spring.redis.host=10.100.50.23
  3. # Redis服务器连接端口
  4. #spring.redis.port=6379
  5. # Redis服务器连接密码(默认为空)
  6. spring.redis.password=
  7. # 连接池最大连接数(使用负值表示没有限制)
  8. spring.redis.pool.max-active=8
  9. # 连接池最大阻塞等待时间(使用负值表示没有限制)
  10. spring.redis.pool.max-wait=-1
  11. # 连接池中的最大空闲连接
  12. spring.redis.pool.max-idle=8
  13. # 连接池中的最小空闲连接
  14. spring.redis.pool.min-idle=0
  15. # 连接超时时间(毫秒)
  16. spring.redis.timeout=0
  17. spring.redis.commandTimeout=5000
  18. # redis.cluster
  19. spring.redis.cluster.nodes=10.100.50.23:6380,10.100.50.23:6381,10.100.50.23:6382,10.100.50.23:6383,10.100.50.23:6384,10.100.50.23:6385

项目入口类加入注解@EnableCaching,添加到缓存

  1. import org.mybatis.spring.annotation.MapperScan;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cache.annotation.EnableCaching;
  5. @SpringBootApplication
  6. @MapperScan("com.example.dao")
  7. @EnableCaching
  8. public class DemoApplication {
  9. public static voidmain(String[] args) {
  10. SpringApplication.run(DemoApplication.class,args);
  11. }
  12. }

自定义redis配置,加入集群

  1. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  2. import com.fasterxml.jackson.annotation.PropertyAccessor;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.data.redis.connection.RedisConnectionFactory;
  9. import org.springframework.data.redis.core.RedisTemplate;
  10. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  11. import org.springframework.data.redis.serializer.StringRedisSerializer;
  12. import redis.clients.jedis.HostAndPort;
  13. import redis.clients.jedis.JedisCluster;
  14. import redis.clients.jedis.JedisPoolConfig;
  15. import java.net.UnknownHostException;
  16. import java.util.HashSet;
  17. import java.util.Set;
  18. /**
  19. * @authorzhenhai.zheng
  20. * @describe
  21. *@date 2018/1/23
  22. **/
  23. @Configuration
  24. @ConditionalOnClass({JedisCluster.class})
  25. public class RedisConfig {
  26. @Value("${spring.redis.cluster.nodes}")
  27. privateString clusterNodes;
  28. @Value("${spring.redis.timeout}")
  29. private inttimeout;
  30. @Value("${spring.redis.pool.max-idle}")
  31. private intmaxIdle;
  32. @Value("${spring.redis.pool.max-wait}")
  33. private longmaxWaitMillis;
  34. @Value("${spring.redis.commandTimeout}")
  35. private intcommandTimeout;
  36. @Bean
  37. publicJedisCluster getJedisCluster() {
  38. String[] cNodes = clusterNodes.split(",");
  39. Set<HostAndPort> nodes =new HashSet<>();
  40. //分割出集群节点
  41. for(String node : cNodes) {
  42. String[] hp = node.split(":");
  43. nodes.add(newHostAndPort(hp[0],Integer.parseInt(hp[1])));
  44. }
  45. JedisPoolConfig jedisPoolConfig =new JedisPoolConfig();
  46. jedisPoolConfig.setMaxIdle(maxIdle);
  47. jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
  48. //创建集群对象
  49. // JedisCluster jedisCluster = new JedisCluster(nodes,commandTimeout);
  50. return newJedisCluster(nodes,commandTimeout,jedisPoolConfig);
  51. }
  52. /**
  53. * 设置数据存入redis 的序列化方式
  54. *</br>redisTemplate序列化默认使用的jdkSerializeable,存储二进制字节码,导致key会出现乱码,所以自定义
  55. *序列化类
  56. *
  57. * @paramredisConnectionFactory
  58. */
  59. @Bean
  60. publicRedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)throws UnknownHostException {
  61. RedisTemplate<Object,Object> redisTemplate = newRedisTemplate<>();
  62. redisTemplate.setConnectionFactory(redisConnectionFactory);
  63. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer =new Jackson2JsonRedisSerializer(Object.class);
  64. ObjectMapper objectMapper =new ObjectMapper();
  65. objectMapper.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
  66. objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  67. jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
  68. redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
  69. redisTemplate.setKeySerializer(newStringRedisSerializer());
  70. redisTemplate.afterPropertiesSet();
  71. return redisTemplate;
  72. }
  73. }

Service实现类中,自动注入jedisCluster

  1. @Autowired
  2. private JedisCluster jedisCluster;

并写入一个测试方法

  1. public String findRedis() {
  2. jedisCluster.set("userName", "hello wenqy");
  3. return jedisCluster.get("userName");
  4. }

在控制层加入调用刚才的service方法

  1. @RequestMapping("/redis")
  2. public String findRedis() {
  3. return userService.findRedis();
  4. }

测试

在findRedis方法中打断点,第一次访问时建立缓存,第二次访问发现没有进入该函数。但返回的结果是一样的。

最后访问

SouthEast

spring boot集成redis进行数据缓存功能

  1. @Cacheable 表明Spring在调用方法之前,首先应该在缓存中查找方法的返回值。如果这个值能够找到,就会返回缓存的值。否则的话,这个方法就会被调用,返回值会放到缓存之中
  2. @cacheput 表明Spring应该将方法的返回值放到缓存中。在方法的调用前并不会 检查缓存,方法始终都会被调用
  3. @cacheevict 表明Spring应该在缓存中清除一个或多个条目
  4. @caching 这是一个分组的注解,能够同时应用多个其他的缓存注解
  5. @cacheconfig 可以在类层级配置一些共用的缓存配置

项目地址https://gitee.com/zhenhai_zheng/springboot_rediscluster.git

将相关注解添加到接口方法上即可

  1. /**
  2. * 指定id的数据
  3. * @param id
  4. * @return
  5. */
  6. @Cacheable(value = "user_",key = "#root.caches[0].name+#id")
  7. @RequestMapping("get/{id}")
  8. public User get(@PathVariable("id") String id){
  9. User user = userService.getUser(id);
  10. return user;
  11. }
  12. /**
  13. *
  14. * @param user
  15. */
  16. @RequestMapping("/updateUser")
  17. @CachePut(value = "user_",key = "#root.caches[0].name+#user.id")
  18. public void updateUser(User user){
  19. userService.updateByPrimaryKey(user);
  20. }
  21. /**
  22. *
  23. * @param id
  24. */
  25. @RequestMapping("/delete/{id}")
  26. @CacheEvict(value = "user_",key = "#root.caches[0].name+#id")
  27. public void delete(@PathVariable("id") String id){
  28. userService.deleteByPrimaryKey(id);
  29. }

发表评论

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

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

相关阅读