RedisTemplate操作redis时,key值出现\xac\xed\x00\x05t\x00等前缀

今天在做redis缓存时,存放数据后发现每个key前面都会新增一些字符,比如:
RedisTemplate操作redis时,key值出现\xac\xed\x00\x05t\x00等前缀_第1张图片
其实这个不影响key的读取和删除,但是不太美观。主要原因是因为RedisTemplate默认序列化方式用的是JdkSerializationRedisSerializer,我们把默认的序列化方式改成Jackson2JsonRedisSerializer即可。
具体操作方法为,在项目中任何地方创建redis配置类即可:



import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
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.connection.jedis.JedisConnectionFactory;
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;

/**
 * @author 
 * 

* 2018年4月24日 * TODO 配置redis序列化 如果不配置,无法获取redis正常编码的值 */ @Configuration public class RedisConfig { @Bean public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); JedisConnectionFactory connectionFactory = (JedisConnectionFactory) template.getConnectionFactory(); connectionFactory.setDatabase(0);//切换0号数据库 //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式) Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, Visibility.ANY); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); serializer.setObjectMapper(mapper); //对String值序列化 template.setValueSerializer(serializer); //对hash值序列化 template.setHashValueSerializer(serializer); //使用StringRedisSerializer来序列化和反序列化redis的key值 template.setKeySerializer(new StringRedisSerializer()); //对hash中的field进行序列化 template.setHashKeySerializer(new StringRedisSerializer()); template.afterPropertiesSet(); return template; } }

pom文件需要引入:

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>

你可能感兴趣的:(【redis使用】)