1. 程式人生 > >Redis 使用spring-data-redis的序列化問題

Redis 使用spring-data-redis的序列化問題

我用spring-data-redis 成功的set了 而且也能成功get出來對應的資料~
但是用redis-cli去伺服器直接get資料是提示(nil) 這是什麼原因啊?
正常是get一個不存在的key才會這樣的

突然想起spring-data-redis 對 key 和 value 都進行了序列化 變成byte[] 再呼叫對應的redis java client進行儲存的。 那應該就是通過spring-data-redis進入redis的key變了

原因其實就出現在這裡,解決的辦法就是手動定義序列化的方法,spring-data-redis中還提供了一個序列化的類專門針對string型別的序列化org.springframework.data.redis.serializer.StringRedisSerializer這個類,可以在xml裡面指定:

<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"  
    p:connection-factory-ref="jedisConnectionFactory">  
    <property name="keySerializer">  
        <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />  
    </property
> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <property name="hashKeySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"
/> </property> <property name="hashValueSerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> </bean>

如果沒有特殊的設定,key 和 value 都是使用 defaultSerializer = new JdkSerializationRedisSerializer(); 進行序列化的。

對於 key = “AAAA” value = “cccc” 的情況, server 端執行的情況如下

“SET” “\xac\xed\x00\x05t\x00\x04AAAA” “\xac\xed\x00\x05t\x00\x04cccc”
“GET” “\xac\xed\x00\x05t\x00\x04AAAA”

如果專案中只使用了string的 key 和 value ,顯然這樣不適合在sever上進行debug

通過上面的配置,可以改成使用StringRedisSerializer對 key 和 value 進行序列化