一、SpringBoot 集成Redis 做缓存

1.1、 添加依赖

  1. <!-- redis依赖 -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-redis</artifactId>
  5. </dependency>
  6. //线程池
  7. <dependency>
  8. <groupId>org.apache.commons</groupId>
  9. <artifactId>commons-pool2</artifactId>
  10. <version>2.6.1</version>
  11. </dependency>

1.2、配置文件(哨兵)

  1. spring:
  2. redis:
  3. database: 0
  4. sentinel:
  5. master: 'mymaster'
  6. nodes:
  7. - "redis://127.0.0.1:26383"
  8. - "redis://127.0.0.1:26382"
  9. - "redis://127.0.0.1:26381"
  10. # password
  11. lettuce:
  12. pool:
  13. # 连接池最大连接数 默认8 ,负数表示没有限制
  14. max-active: 8
  15. # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认-1
  16. max-wait: -1
  17. # 连接池中的最大空闲连接 默认8
  18. max-idle: 8
  19. # 连接池中的最小空闲连接 默认0
  20. min-idle: 0
  21. redisson:
  22. file: classpath:redisson.yml

1.3、 Redis 缓存配置

  1. @Slf4j
  2. @Configuration
  3. @EnableCaching
  4. public class RedisConfig extends CachingConfigurerSupport {
  5. private RedisSerializer serializer(){
  6. Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
  7. ObjectMapper objectMapper = new ObjectMapper();
  8. // 将类型序列化到属性json字符串中
  9. // objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
  10. objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
  11. // 对于找不到匹配属性的时候忽略报错
  12. objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  13. // 不包含任何属性的bean也不报错
  14. objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
  15. serializer.setObjectMapper(objectMapper);
  16. return serializer;
  17. }
  18. /**
  19. * 如使用注解的话需要配置cacheManager
  20. *
  21. * @return
  22. */
  23. @Bean
  24. public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
  25. //覆盖默认的序列化
  26. RedisSerializer serializer = serializer();
  27. //默认配置
  28. RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration
  29. .defaultCacheConfig()
  30. //设置默认超过期时间是7天
  31. .entryTtl(Duration.ofDays(7))
  32. .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer));
  33. return RedisCacheManager.builder(redisConnectionFactory)
  34. .cacheDefaults(defaultCacheConfig)
  35. .build();
  36. }
  37. @Bean
  38. public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
  39. //覆盖默认的序列化
  40. RedisSerializer serializer = serializer();
  41. StringRedisSerializer stringRedisSerializer = StringRedisSerializer.UTF_8;
  42. RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
  43. redisTemplate.setConnectionFactory(redisConnectionFactory);
  44. redisTemplate.setKeySerializer(stringRedisSerializer);
  45. redisTemplate.setHashKeySerializer(stringRedisSerializer);
  46. redisTemplate.setHashValueSerializer(serializer);
  47. redisTemplate.setValueSerializer(serializer);
  48. redisTemplate.setDefaultSerializer(serializer);
  49. redisTemplate.afterPropertiesSet();
  50. return redisTemplate;
  51. }
  52. @Bean
  53. @Override
  54. public CacheErrorHandler errorHandler() {
  55. // 异常处理,当Redis发生异常时,打印日志,但是程序正常走
  56. log.info("初始化 -> [{}]", "Redis CacheErrorHandler");
  57. CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {
  58. @Override
  59. public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
  60. log.error("Redis occur handleCacheGetError:key -> [{}]", key, e);
  61. }
  62. @Override
  63. public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {
  64. log.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", key, value, e);
  65. }
  66. @Override
  67. public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) {
  68. log.error("Redis occur handleCacheEvictError:key -> [{}]", key, e);
  69. }
  70. @Override
  71. public void handleCacheClearError(RuntimeException e, Cache cache) {
  72. log.error("Redis occur handleCacheClearError:", e);
  73. }
  74. };
  75. return cacheErrorHandler;
  76. }
  77. }

二、Spring 集成 Redisson

2.1、添加依赖

  1. <dependency>
  2. <groupId>org.redisson</groupId>
  3. <artifactId>redisson-spring-boot-starter</artifactId>
  4. <version>3.16.6</version>
  5. </dependency>

2.2、redisson 配置

  • application.yml ```yaml spring: redis: redisson:
    1. file: classpath:redisson.yml
  1. - redisson.yml (哨兵模式)
  2. ```yaml
  3. sentinelServersConfig:
  4. #空闲链接超时
  5. idleConnectionTimeout: 10000
  6. #连接超时
  7. connectTimeout: 10000
  8. # 超时
  9. timeout: 3000
  10. # 重试次数
  11. retryAttempts: 3
  12. # 重试间隔
  13. retryInterval: 1500
  14. # 失败重连间隔
  15. failedSlaveReconnectionInterval: 3000
  16. # 失败检查
  17. failedSlaveCheckInterval: 60000
  18. # 密码
  19. password: null
  20. subscriptionsPerConnection: 5
  21. clientName: null
  22. # 负载均衡
  23. loadBalancer: !<org.redisson.connection.balancer.RoundRobinLoadBalancer> {}
  24. subscriptionConnectionMinimumIdleSize: 1
  25. subscriptionConnectionPoolSize: 50
  26. slaveConnectionMinimumIdleSize: 24
  27. slaveConnectionPoolSize: 64
  28. masterConnectionMinimumIdleSize: 24
  29. masterConnectionPoolSize: 64
  30. readMode: "SLAVE"
  31. subscriptionMode: "SLAVE"
  32. sentinelAddresses:
  33. - "redis://127.0.0.1:26383"
  34. - "redis://127.0.0.1:26382"
  35. - "redis://127.0.0.1:26381"
  36. masterName: "mymaster"
  37. database: 0
  38. threads: 16
  39. nettyThreads: 32
  40. codec: !<org.redisson.codec.JsonJacksonCodec> {}
  41. transportMode: "NIO"

三、参考

  1. https://docs.spring.io/spring-data/redis/docs/2.2.0.RELEASE/reference/html/#reference
  2. https://github.com/h-dj/Spring-Learning.git