Spring Data操作Redis時,發現key值出現 \xac\xed\x00\x05t\x00\tb
先說現象吧,通過redisTemplate下的opsForHash方法存儲hash類型的值,操作成功以后,去redis控制台顯示keys * 的時候,發現一個奇怪的現象,插入的hash類型的key前面會有一堆的\xac\xed\x00\x05t\x00\tb 這種東西,見圖1:
分析spring-data的org.springframework.data.redis.core.RedisTemplate源代碼以后發現:
private RedisSerializer<?> defaultSerializer = new JdkSerializationRedisSerializer(); private RedisSerializer keySerializer = null; private RedisSerializer valueSerializer = null; private RedisSerializer hashKeySerializer = null; private RedisSerializer hashValueSerializer = null; private RedisSerializer<String> stringSerializer = new StringRedisSerializer();
因為spring操作redis是在jedis客戶端基礎上進行的,而jedis客戶端與redis交互的時候協議中定義是用byte類型交互,jedis中提供了string類型轉為byte[]類型,但是看到spring-data-redis中RedisTemplate<K, V>在操作的時候k,v是泛型的,所以RedisTemplate中有了上面那段代碼,在沒有特殊定義的情況下,spring默認采用defaultSerializer = new JdkSerializationRedisSerializer();來對key,value進行序列化操作,在經過查看JdkSerializationRedisSerializer中對序列化的一系列操作,發現如下代碼:
private Converter<Object, byte[]> serializer = new SerializingConverter(); public byte[] serialize(Object object) { if (object == null) { return SerializationUtils.EMPTY_ARRAY; } try { return serializer.convert(object); } catch (Exception ex) { throw new SerializationException("Cannot serialize", ex); } }
序列化支持的是Object對象,調用了SerializingConverter類下的convert方法轉換對象,轉換對象的方法是:
private final Serializer<Object> serializer; /** * Serializes the source object and returns the byte array result. */ public byte[] convert(Object source) { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(128); try { this.serializer.serialize(source, byteStream); return byteStream.toByteArray(); } catch (Throwable ex) { throw new SerializationFailedException("Failed to serialize object using " + this.serializer.getClass().getSimpleName(), ex); } }
原因其實就出現在這里,解決的辦法就是手動定義序列化的方法,spring-data-redis中還提供了一個序列化的類專門針對string類型的序列化org.springframework.data.redis.serializer.StringRedisSerializer這個類,可以在xml里面指定:
@Bean public RedisTemplate<String, Serializable> serialRedisTemplate(){ RedisTemplate<String, Serializable> template = new RedisTemplate<>(); template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); template.setConnectionFactory(palmRedisConnectionFactory()); return template; }
修改后,的存儲結果: