Search code examples
redisspring-data

Using RedisTemplate set a value but get Nil from Terminal Redis-CLI


1.Set key name with alex using Spring data redis Library.

 @Test
public void testOne() throws Exception {
    redisTemplate.opsForValue().set("name","alex");
}

2.Try get name from Terminal with redis-cli but get Nil

127.0.0.1:6379> get name
(nil)

3.However alex can be retrieve like this

Object hello = redisTemplate.opsForValue().get("name");
System.out.println(hello);
-----
alex

Can anyone explain this, thanks!


Solution

  • RedisTemplate converts keys and values depending on the configured RedisSerializers (see 6.7 Serializers). The default is JdkSerializationRedisSerializer.

    Given the String name the actual key in redis looks like:

    GenericJackson2JsonRedisSerializer  : "name"
    JacksonJsonRedisSerializer:         : "name"
    Jackson2JsonRedisSerializer:        : "name"
    JdkSerializationRedisSerializer     : \xac\xed\x00\x05t\x00\x04name
    OxmSerializer with XStreamMarshaller: <string>name</string>
    StringRedisSerializer               : name
    

    So in case you intend to just work with Strings the convenience classes like StringRedisTemplate might be a good choice.