Overview
RedisTemplate
The default is to use a serializer based on JDK
, so the data stored in if it is Redis
not deserialized, see the result is like this:
Can see, there is garbled, at the program level, will not affect the operation of the program, but when the data errors, the data to troubleshoot, will not be able to.
Serializer
In spring Data Redis, the conversion between the user-defined type and the stored data (and vice versa) is org.springframework.data.redis.serializer
handled by the class under the package.
This package contains two types of serializers that are responsible for the serialization process:
RedisSerializer
a bidirectional serializer based on
RedisElementReader
Reading and RedisElementWriter
writing of elements (2.0 introduced)
The main difference between these two types of serializers is that the RedisSerializer
primary serialization is byte[],RedisElementReader/RedisElementWriter
used ByteBuffer
.
RedisSerializer
There are several implementations of the serializer based, which can be used directly, such as:
StringRedisSerializer
JdkSerializationRedisSerializer
Default
OxmSerializer
(Dependent on Spring OXM
)
Jackson2JsonRedisSerializer/GenericJackson2JsonRedisSerializer
(Dependent on jackson
)
Scope of serialization
Serialization can be applied to,,, Key
Value
on, HashKey
HashValue
in RedisTemplate
, four of which correspond to:
keySerializer
, valueSerializer
, hashKeySerializer
,hashValueSerializer
JSON-based serialization
Introducing Jackson's MAVEN dependency:
<jackson.databind.version>2.8.5</jackson.databind.version><!-- jackson-databind --><dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.databind.version}</version></dependency>
To configure the serializer:
<!-- 缓存序列化方式 --><!--对key的默认序列化器。默认值是StringSerializer --><bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" /><!--是对value的默认序列化器,默认值是取自DefaultSerializer的JdkSerializationRedisSerializer。 --><bean id="genericJackson2JsonRedisSerializer" class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
Reconfigure Redistemplate:
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory"/> <property name="keySerializer" ref="stringRedisSerializer" /> <property name="valueSerializer" ref="stringRedisSerializer"/> <property name="hashKeySerializer" ref="stringRedisSerializer"/> <property name="hashValueSerializer" ref="genericJackson2JsonRedisSerializer" /></bean>
Rerun the example of the previous section to get the following result:
Example description
1. 查看redis的管理工具是:RedisDesktopManager,:https://redisdesktop.com/download
Spring data Redis Getting Started sample: Serialization (four)