redis在SpringBoot中的配置及加载
@EnableCaching
@Configuration
public class RedisConfig {
@Value("${spring.redis.decryptPassword}")
private String password;
@Value("${aes.key}")
private String key;
@Bean
@ConfigurationProperties(prefix = "spring.redis.pool")
public JedisPoolConfig getRedisConfig() {
JedisPoolConfig config = new JedisPoolConfig();
return config;
}
@Bean
@ConfigurationProperties(prefix = "spring.redis")
public JedisConnectionFactory getConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setUsePool(true);
JedisPoolConfig config = getRedisConfig();
factory.setPoolConfig(config);
factory.setPassword(new String(AesUtil.decrypt(Base64Utils.decodeFromString(password), key)));
return factory;
}
@Bean
public StringRedisTemplate stringRedisTemplate() {
JedisConnectionFactory factory = getConnectionFactory();
StringRedisTemplate template = new StringRedisTemplate(factory);
return template;
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
JedisConnectionFactory factory = getConnectionFactory();
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
template.setKeySerializer(stringRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
@Primary
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
redisCacheManager.setDefaultExpiration(60 * 60 * 6L);
return redisCacheManager;
}
}