Всъщност по подразбиране и spring-session, и spring-cache всъщност се конфигурират чрез spring-boot с RedisConnectionFactory
bean с име connectionFactory
.Два начина да направите това.
-
направи
spring-session
за да използвате различенconnectionFactory
bean екземпляр и оставете spring-cache, за да използватеconnectionFactory
по подразбиране . И по-долу е примерно решение:@Configuration public class RedisHttpSessionConfig { @Bean StringRedisSerializer stringRedisSerializer() { return new StringRedisSerializer(); } @Bean RedisConnectionFactory redisHttpSessionConnectionFactory() { RedisConnectionFactory redisHttpSessionConnectionFactory = null; // ... add your codes here return redisHttpSessionConnectionFactory; } @Bean public RedisTemplate<Object, Object> sessionRedisTemplate( RedisConnectionFactory redisHttpSessionConnectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>(); template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); template.setDefaultSerializer(GenericJackson2JsonRedisSerializer()); template.setConnectionFactory(redisHttpSessionConnectionFactory); return template; } }
-
направи
spring-cache
за да използвате различенconnectionFactory
bean екземпляр и оставете spring-session, за да използватеconnectionFactory
по подразбиране . И по-долу е примерно решение:@Configuration public class RedisCacheConfig { @Bean StringRedisSerializer stringRedisSerializer() { return new StringRedisSerializer(); } @Bean RedisConnectionFactory redisCacheConnectionFactory() { RedisConnectionFactory redisCacheConnectionFactory = null; // ... add your codes here return redisCacheConnectionFactory; } @Bean RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisCacheConnectionFactory) { RedisTemplate<Object, Object> redisTemplate = new RedisTemplate(); redisTemplate.setConnectionFactory(redisCacheConnectionFactory); redisTemplate.setKeySerializer(this.stringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return redisTemplate; } @Bean(name = "stringRedisTemplate") public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisCacheConnectionFactory) throws UnknownHostException { StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(); stringRedisTemplate.setConnectionFactory(redisCacheConnectionFactory); stringRedisTemplate.setKeySerializer(this.stringRedisSerializer()); stringRedisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return stringRedisTemplate; } @Bean CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate); cacheManager.setDefaultExpiration(600l); cacheManager.setUsePrefix(true); return cacheManager; } }