De fato, por padrão, tanto spring-session quanto spring-cache são configurados pelo spring-boot com um
RedisConnectionFactory
bean nomeado como connectionFactory
.Duas maneiras de fazer isso. -
makespring-session
para usar umconnectionFactory
diferente bean e deixe o spring-cache para usar o padrãoconnectionFactory
. E abaixo está uma solução de exemplo:
@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; } }
-
makespring-cache
para usar umconnectionFactory
diferente bean e deixe spring-session para usar o padrãoconnectionFactory
. E abaixo está uma solução de exemplo:
@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; } }