经查阅资料,是RedisTemplate默认序列化方式用的是JdkSerializationRedisSerializer,此时我将key序列化方式改成StringRedisSerializer,将value序列化方式改为Jackson2JsonRedisSerializer
代码如下:
//序列化为String 防止key值出现\xac\xed\x00\x05t\x00前缀
RedisSerializer stringSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);//序列化为Json
redisTemplate.setKeySerializer(stringSerializer);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashKeySerializer(stringSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
拓展
//将手机号或者邮箱存为Key 验证码存为Value
redisTemplate.opsForValue().set(info, code);
//设置Redis验证码过期时间为5分钟
redisTemplate.expire(info, 5, TimeUnit.MINUTES);
Long expire = redisTemplate.boundHashOps(info).getExpire();
System.out.println("redis有效时间:" + expire + "分钟");