作用 处理Springboot使用 RedisTemplate过程中的编码问题
现象如下,看数据的时候不方便
所以添加一下的配置类之后,就可以了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
package com.htb.beidawebspringboot10redis.config;
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;
import java.net.UnknownHostException; import java.text.SimpleDateFormat;
/** * @Description:Redis通用配置类 * @Author 16221 * @Date 2020/4/23 **/ @Configuration public class RedisConfig { @Bean //不指定id的话bean 的id就是方法名 //返回结果就是spring中管理的bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate<Object, Object> template = new RedisTemplate<>();
//ObjectMapper 指定在转成json的时候的一些转换规则 ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
template.setConnectionFactory(redisConnectionFactory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); //把自定义objectMapper设置到jackson2JsonRedisSerializer中(可以不设置,使用默认规则) jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
//RedisTemplate默认的序列化方式使用的是JDK的序列化 //设置了key的序列化方式 template.setKeySerializer(new StringRedisSerializer()); //设置了value的序列化方式 template.setValueSerializer(jackson2JsonRedisSerializer); return template; } } |
设置其他的序列化方式使用json形式
RedisTemplate,默认序列化的时候,用的RedisTemplate里面的一个RedisSerializer对象的string方法
转成了byte[] bytes
就是说最终是转成了字节流
所以并不是通过json串的方式,这样出来的结果就不是json串