@Configuration
@EnableCaching
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig extends CachingConfigurerSupport {
private static final Logger log = LoggerFactory.getLogger(RedisConfig.class);
/**
* Set the default expiration time of redis data, default 2 hours
* Set the @cacheable serialization method
*/
@Bean
public RedisCacheConfiguration redisCacheConfiguration(){
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
configuration = configuration.serializeValuesWith(RedisSerializationContext.
SerializationPair.fromSerializer(fastJsonRedisSerializer)).entryTtl(Duration.ofHours(6));
return configuration;
}
@SuppressWarnings("all")
@Bean(name = "redisTemplate")
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
//Serialization
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
// The serialization of value values uses fastJsonRedisSerializer
template.setValueSerializer(fastJsonRedisSerializer);
template.setHashValueSerializer(fastJsonRedisSerializer);
// Turn on AutoType globally, which is convenient for development and uses the global method
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
// It is recommended to use this method, specify a whitelist in a small range to solve the problem of autoType is not
ParserConfig.getGlobalInstance().addAccept("");
// The serialization of key uses StringRedisSerializer
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
System.out.println("=================================================================="+redisConnectionFactory.toString());
System.out.println("============================="+redisConnectionFactory.getConnection()+"=====================================");
System.out.println("================================"+template.toString()+"==================================");
return template;
}
/**
* Custom cache key generation policy, which will be used by default
*/
@Bean
@Override
public KeyGenerator keyGenerator() {
return (target, method, params) -> {
Map<String,Object> container = new HashMap<>(3);
Class<?> targetClassClass = target.getClass();
// Class address
container.put("class",targetClassClass.toGenericString());
// Method name
container.put("methodName",method.getName());
// Package name
container.put("package",targetClassClass.getPackage());
// Parameter list
for (int i = 0; i < params.length; i++) {
container.put(String.valueOf(i),params[i]);
}
// Convert to JSON string
String jsonString = JSON.toJSONString(container);
// Do SHA256 Hash calculation and get a SHA256 digest as a key
return DigestUtils.sha256Hex(jsonString);
};
}
@Bean
@Override
public CacheErrorHandler errorHandler() {
// Exception handling, when Redis exception occurs, the log is printed, but the program goes normally
log.error("Initialization -> [{}]", "Redis CacheErrorHandler");
return new CacheErrorHandler() {
@Override
public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
log.error("Redis occur handleCacheGetError:key -> [{}]", key, e);
}
@Override
public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {
log.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", key, value, e);
}
@Override
public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) {
log.error("Redis occur handleCacheEvictError:key -> [{}]", key, e);
}
@Override
public void handleCacheClearError(RuntimeException e, Cache cache) {
log.error("Redis occur handleCacheClearError:", e);
}
};
}
}