开发依赖 | 版本 |
---|---|
Spring Boot | 2.6.6 |
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
<dependency>
<groupId>redis.clientsgroupId>
<artifactId>jedisartifactId>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
dependency>
dependencies>
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));
}
}
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);
}
}
发现没有,写入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);
}
}
这下就正确了