1. #Redis服务器地址
    2. spring.redis.host=192.168.140.136
    3. #Redis服务器连接端口
    4. spring.redis.port=6379
    5. #Redis数据库索引(默认为0)
    6. spring.redis.database= 0
    7. #连接超时时间(毫秒)
    8. spring.redis.timeout=1800000
    9. #连接池最大连接数(使用负值表示没有限制)
    10. spring.redis.lettuce.pool.max-active=20
    11. #最大阻塞等待时间(负数表示没限制)
    12. spring.redis.lettuce.pool.max-wait=-1
    13. #连接池中的最大空闲连接
    14. spring.redis.lettuce.pool.max-idle=5
    15. #连接池中的最小空闲连接
    16. spring.redis.lettuce.pool.min-idle=0
    1. @EnableCaching
    2. @Configuration
    3. public class RedisConfig extends CachingConfigurerSupport {
    4. @Bean
    5. public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
    6. RedisTemplate<String, Object> template = new RedisTemplate<>();
    7. RedisSerializer<String> redisSerializer = new StringRedisSerializer();
    8. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    9. ObjectMapper om = new ObjectMapper();
    10. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    11. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    12. jackson2JsonRedisSerializer.setObjectMapper(om);
    13. template.setConnectionFactory(factory);
    14. //key序列化方式
    15. template.setKeySerializer(redisSerializer);
    16. //value序列化
    17. template.setValueSerializer(jackson2JsonRedisSerializer);
    18. //value hashmap序列化
    19. template.setHashValueSerializer(jackson2JsonRedisSerializer);
    20. return template;
    21. }
    22. @Bean
    23. public CacheManager cacheManager(RedisConnectionFactory factory) {
    24. RedisSerializer<String> redisSerializer = new StringRedisSerializer();
    25. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    26. //解决查询缓存转换异常的问题
    27. ObjectMapper om = new ObjectMapper();
    28. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    29. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    30. jackson2JsonRedisSerializer.setObjectMapper(om);
    31. // 配置序列化(解决乱码的问题),过期时间600秒
    32. RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
    33. .entryTtl(Duration.ofSeconds(600))
    34. .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
    35. .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
    36. .disableCachingNullValues();
    37. RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
    38. .cacheDefaults(config)
    39. .build();
    40. return cacheManager;
    41. }