转载链接https://blog.csdn.net/sy793314598/article/details/80719224
@Bean public RedisCacheManager cacheManager(RedisConnectionFactory factory) { RedisSerializer<String> redisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); //解决查询缓存转换异常的问题 ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); //配置序列化(解决乱码的问题) RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() // .entryTtl(Duration.ZERO) .entryTtl(Duration.ofSeconds(15L)) //设置默认缓存15秒 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) .disableCachingNullValues(); Set<String> cacheNames = new HashSet<>(); cacheNames.add("emp"); cacheNames.add("dept"); // 对每个缓存空间应用不同的配置 Map<String, RedisCacheConfiguration> configMap = new HashMap<>(); configMap.put("emp", config); configMap.put("dept", config.entryTtl(Duration.ofSeconds(30L))); //这个缓存空间30秒 RedisCacheManager cacheManager = RedisCacheManager.builder(factory) .cacheDefaults(config) .initialCacheNames(cacheNames)// 注意这两句的调用顺序,一定要先调用该方法设置初始化的缓存名,再初始化相关的配置 .withInitialCacheConfigurations(configMap) .build(); return cacheManager;