我们需要写一个配置文件:redisCaccheConf
先写结论:纯手打,直接复制过去可能会飘红,不确定有那个字母按错
实现了key的唯一性以及序列化问题
@Configuration
@EnableCaching
public class RedisCacheConf extends CachingConfigurerSupport{
@Autowired
private RedisTemplate redisTemplate;
/**
*生成key的策略
*此方法会更具类名,方法名以及入参生成唯一的一个key
*/
@Bean
public KeyGenerator keyGenerator(){
return new KeyGenerator(){
@Override
public Object generate(Object target,Method method,Object... params){
StringBuilder sb = new StringBuilder();
//各个参数之间用"_"链接
sb.append(target.getClass().getName).append("_");//类名
sb.append(method.getName()).append("_");//方法名
for(Object obj:params){
if(obj!=null){
sb.append(obj.toString()).append("_");
}else{
sb.append("/").append("_");
}
}
return sb.toString();
}
}
}
/**
*配置redis缓存管理对象
*配置过期时间,序列化
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory){
RedisSerializer<String> redisSerializer=new StringRedisSerializer();
Jackon2JsonRedisSerializer jackon2JsonRedisSerializer = new Jackon2JsonRedisSerializer(Object.class);
//设置5分钟过期时间
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(5));
//解决序列化问题,防止乱码
RedisCacheConfiguration redisCacheConfiguration = config
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new Jackson2JsonRedisSerializer<>(Object.class)));
RedisCacheManager redisCacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(redisCacheConfiguration).bulid();
return redisCacheManager;
}
/**
* 实例化 RedisTemplate 对象
* @return
*/
@Bean(name = "redisTemplate")
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackon2JsonRedisSerializer jackon2JsonRedisSerializer =new Jackon2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackon2JsonRedisSerializer.setObjectMapper(om);
redisTemplate.setConnectionFactory(factory);
redisTemplate.setKeySerializer(redisSerializer);
redisTemplate.setHashValueSerializer(jackon2JsonRedisSerializer);
redisTemplate.setValueSerializer(jackon2JsonRedisSerializer);
return redisTemplate;
}
}