RedisTemplate默认的序列化方式为jdkSerializeable,会把对象序列化存储到Redis中(二进制形式),StringRedisTemplate的默认序列化方式为StringRedisSerializer。
通过配置,将RedisTemplate的序列化方式进行更改
1 import org.springframework.context.annotation.Bean;
2 import org.springframework.context.annotation.Configuration;
3 import org.springframework.data.redis.connection.RedisConnectionFactory;
4 import org.springframework.data.redis.core.RedisTemplate;
5 import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
6 import org.springframework.data.redis.serializer.StringRedisSerializer;
7
8 /**
9 * @ClassName:RedisConfig
10 * @Author:微微亮
11 * @Description:
12 * @Date:2020/11/11 20:48
13 * @Version: 1.0
14 */
15 @Configuration
16 public class RedisConfig {
17
18 @Bean//参数--一个工厂
19 public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
20 RedisTemplate redisTemplate = new RedisTemplate();
21 //给redis模板先设置连接工厂,在设置序列化规则
22 redisTemplate.setConnectionFactory(redisConnectionFactory);
23 //设置序列化规则
24 redisTemplate.setKeySerializer(new StringRedisSerializer());
25 redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer());
26 redisTemplate.setHashKeySerializer(genericJackson2JsonRedisSerializer());
27 redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer());
28 return redisTemplate;
29 }
30
31 @Bean
32 public GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer(){
33 return new GenericJackson2JsonRedisSerializer();
34 }
35 }
这样在其他代码中
@Autowired
private RedisTemplate redisTemplate;
就可以自动装配(注入)使用了。