本文开发环境介绍
开发依赖 | 版本 |
---|---|
Spring Boot | 2.6.6 |
pom.xml依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> </dependencies>
redis保存数据后出现\xac\xed\x00\x05t\x00的问题
测试代码
public class RedisTemplateTest extends DemoRedisTestBase { @SneakyThrows @Test void testSet() { String key = String.join(":", "user", RandomStringUtils.randomAlphabetic(10)); Map<String, String> value = new HashMap<>(); value.put("id", RandomStringUtils.randomAlphabetic(10)); value.put("name", RandomStringUtils.randomAlphabetic(10)); redisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(value)); } }
查看写入redis的数据
127.0.0.1:6379> keys *user* 1) "\xac\xed\x00\x05t\x00\x0fuser:mnaurYPzBt"
这是因为默认把key和value的值序列化成**byte[]**格式。
解决办法
@Configuration public class RedisTemplateBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if(RedisTemplate.class.isAssignableFrom(bean.getClass())) { RedisTemplate redisTemplate = (RedisTemplate)bean; StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); redisTemplate.setKeySerializer(stringRedisSerializer); redisTemplate.setValueSerializer(stringRedisSerializer); } return bean; } }
再次运行测试代码,结果如下
127.0.0.1:6379> keys *user*
1) "user:PvwBNJFUKn"
2) "\xac\xed\x00\x05t\x00\x0fuser:mnaurYPzBt"
127.0.0.1:6379> get user:PvwBNJFUKn
"{\"name\":\"mfEESamnux\",\"id\":\"OFPcKTgwAm\"}"
写一个带有效期的数据
public class RedisTemplateTest extends DemoRedisTestBase { @SneakyThrows @Test void testSet() { String key = String.join(":", "user", RandomStringUtils.randomAlphabetic(10)); Map<String, String> value = new HashMap<>(); value.put("id", RandomStringUtils.randomAlphabetic(10)); value.put("name", RandomStringUtils.randomAlphabetic(10)); redisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(value), 1L); String json = redisTemplate.opsForValue().get(key); System.out.println(json); } }
指定了第3个参数 1L
,运行查看数据
发现没有,写入redis的数据最前面有一个不认识的字符 \x00
,其实是想当然的用错了方法,正确设置过期时间的姿势应该是这样
public class RedisTemplateTest extends DemoRedisTestBase { @SneakyThrows @Test void testSet() { String key = String.join(":", "user", RandomStringUtils.randomAlphabetic(10)); Map<String, String> value = new HashMap<>(); value.put("id", RandomStringUtils.randomAlphabetic(10)); value.put("name", RandomStringUtils.randomAlphabetic(10)); redisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(value), 1L, TimeUnit.DAYS); String json = redisTemplate.opsForValue().get(key); System.out.println(json); } }
应该使用这个4个参数的方法才是设置过期时间,再运行下
这下就正确了
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持好代码网。