首先建立配置类,实例化2个CacheManager的bean,且实现json序列化,其中一个设为primary,,然后,在实际的service层注解中,用cachemanage引用这个两个不同的bean,,
@Configuration public class RedisManager { @Bean @Primary public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { //初始化一个RedisCacheWriter RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory); //设置CacheManager的值序列化方式为json序列化 RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer(); RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(jsonSerializer); RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig() .serializeValuesWith(pair).entryTtl(Duration.ofHours(3)); //设置默认超过时期是3小时 //初始化RedisCacheManager return new RedisCacheManager(redisCacheWriter, defaultCacheConfig); } @Bean public CacheProperties cacheProperties() { CacheProperties cp = new CacheProperties(); //cp.getRedis().setTimeToLive(Duration.ofHours(4)); return cp; } @Bean(name = "zhouyi") public RedisCacheManager cacheManager1(RedisConnectionFactory redisConnectionFactory) { //初始化一个RedisCacheWriter RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory); //设置CacheManager的值序列化方式为json序列化 RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer(); RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(jsonSerializer); RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig() .serializeValuesWith(pair).entryTtl(Duration.ZERO); //设置默认超过时期为永久 //初始化RedisCacheManager return new RedisCacheManager(redisCacheWriter, defaultCacheConfig); } }
在实际的操作中,通过cacheManager注解引用
@Cacheable(cacheNames = "ZhouyiYao",key = "#rawId+':'+#bianYao",cacheManager = "zhouyi") public ZhouyiYao getZhaoyiYaoByZhanbu(Integer rawId, Integer bianYao) { return zhouyiYaoMapper.getZhaoyiYaoByZhanbu(rawId, bianYao); }
实际操作,因为初始化时,yml中需要提升连接超时时间
spring: redis: host: 127.0.0.1 port: 6379 connect-timeout: 15000