再项目使用了redis储存key,测试需要在客户端删除对应的key,发现查询不到对应的key
redis客户端:
发现redisTemplate实际存进去的key会多了几个字符
原因:程序中对key没做序列化存储
如果你用redis客户端查询你想要的key,redisTemplate下面添加这两个属性
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
或者
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
注意如果使用springboot会默认创建JdkSerializationRedisSerializer序列化类,我们需要自己定义redisTemplate对应的bean,且bean的名称必须为redisTemplate,否则springboot会默认创建