@Configuration
@EnableCaching
public class RedisConfiguration extends CachingConfigurerSupport {
@Autowired
private RedisProperties redisProperties;
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
if (params.length == 0) {
return Constants.CACHE_KEY_PREFIX + method.getName();
}
if (params.length == 1) {
Object param = params[0];
if (param != null && !param.getClass().isArray()) {
return Constants.CACHE_KEY_PREFIX + method.getName() + "_" + param;
}
}
return Constants.CACHE_KEY_PREFIX + method.getName() + " [" + StringUtils.arrayToCommaDelimitedString(params) + "]";
}
};
}
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
redisCacheManager.setDefaultExpiration(redisProperties.getExpire());
return redisCacheManager;
}
@Bean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
redisTemplate.setValueSerializer(new RedisSerializer<Object>() {
@Override
public byte[] serialize(Object object) throws SerializationException {
if (object == null) {
return new byte[0];
}
if (!(object instanceof Serializable)) {
throw new IllegalArgumentException("RedisSerializer.serialize requires a Serializable payload "
+ "but received an object of type [" + object.getClass().getName() + "]");
}
return SerializationUtils.serialize((Serializable) object);
}
@Override
public Object deserialize(byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length == 0) {
return null;
}
return SerializationUtils.deserialize(bytes);
}
});
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
public JedisConnectionFactory redisConnectionFactory() {
JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
redisConnectionFactory.setHostName(redisProperties.getHost());
redisConnectionFactory.setPort(redisProperties.getPort());
redisConnectionFactory.setDatabase(redisProperties.getIndex());
redisConnectionFactory.setPassword(redisProperties.getPassword());
return redisConnectionFactory;
}
}