import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
/**
* 自定义redistemplate,方便开发,避免问题
* @param redisConnectionFactory
* @return
*/
@Bean
@SuppressWarnings("all")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(redisConnectionFactory);
//Json序列化配置
//用Jackson解析任何类型的对象
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
ObjectMapper objectMapper= new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
//String的序列化
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//String的key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
//Hash的key采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
//value需要序列化才不会在编译时报错符,value序列化方式使用Jackson来进行序列化
template.setValueSerializer(jackson2JsonRedisSerializer);
//hash的value序列化方式采用Jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
//把所有的properties set进template
template.afterPropertiesSet();
return template;
}
}
自定义RedisTemplate
于 2022-09-27 23:19:31 首次发布