Memang, secara default, baik spring-session dan spring-cache sebenarnya dikonfigurasi oleh spring-boot dengan RedisConnectionFactory
kacang bernama connectionFactory
.Dua cara untuk melakukan ini.
-
buat
spring-session
untuk menggunakanconnectionFactory
yang berbeda bean, dan biarkan spring-cache menggunakanconnectionFactory
default default . Dan di bawah ini adalah contoh solusi:@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; } }
-
buat
spring-cache
untuk menggunakanconnectionFactory
yang berbeda kacang, dan biarkan sesi pegas menggunakanconnectionFactory
default . Dan di bawah ini adalah contoh solusi:@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; } }