Redis序列化對象
GenericToStringSerializer: 可以將任何對象泛化為字符串并序列化哆窿。
JacksonJsonRedisSerializer: 序列化object對象為json字符串。
Jackson2JsonRedisSerializer: 跟JacksonJsonRedisSerializer實際上是一樣的熙兔。
JdkSerializationRedisSerializer: 序列化java對象摆尝,對象必須實現(xiàn)Serializable接口良姆。
StringRedisSerializer: 簡單的字符串序列化蚁堤。
Redis配置:
@Configuration
@EnableCaching
public class RedisConfigurer extends CachingConfigurerSupport {
/*定義緩存數(shù)據(jù) key 生成策略的bean
包名+類名+方法名+所有參數(shù)
*/
@Bean
public KeyGenerator wiselyKeyGenerator(){
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
@Bean
public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate<?, ?> redisTemplate) {
// 創(chuàng)建緩存管理器
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
cacheManager.setDefaultExpiration(3600 * 24);
cacheManager.setUsePrefix(true);
cacheManager.setCachePrefix(new DefaultRedisCachePrefix(":"));
return cacheManager;
}
@Bean
public RedisTemplate redisTemplate(JedisConnectionFactory factory) {
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
RedisTemplate template = new RedisTemplate();
template.setConnectionFactory(factory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashKeySerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
@Bean
public RedisTemplate sessionRedisTemplate(JedisConnectionFactory factory) {
RedisTemplate<Serializable, Session> template = new RedisTemplate();
template.setConnectionFactory(factory);
template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new JdkSerializationRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
使用模板
@Resource
private StringRedisTemplate stringRedisTemplate;
......
@Resource(name = "redisTemplate")
private HashOperations<String, Integer, Serializable> hashOperations;
......
@Resource(name = "sessionRedisTemplate")
private ValueOperations<Serializable, Session> valueOperations;
Spring 緩存注解*@Cacheable的使用
@Cacheable(value = "domainHome", keyGenerator = "wiselyKeyGenerator", unless = "#result.empty")
public List<AuthorityUsers> getDomains(String serverName) {
......
}