ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
RedisTemplate 默认使用的序列化机制为 JdkSerializationRedisSerializer,序列化后的值一般如下图。 ![](https://img.kancloud.cn/ed/9e/ed9e1b137abd71d448fcf10c1bad8ff9_1750x308.png) <br/> 我们可以自定义序列化机制,比如将对象序列化为 JSON 字符串。步骤如下: **1. 自定义 RedisTemplate 模板** ```java @Configuration public class CustomRedisConfig { @Bean("stuRedisTemplate") public RedisTemplate<String, Student> stuRedisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Student> template = new RedisTemplate<>(); template.setConnectionFactory(factory); //采用JSON的序列化机制 Jackson2JsonRedisSerializer<Student> ser = new Jackson2JsonRedisSerializer<>(Student.class); template.setDefaultSerializer(ser); return template; } } ``` ![](https://img.kancloud.cn/44/79/44795f04fb785a18999296056a2fc95d_1571x564.png) <br/> **2. 使用自定义的模板类操作 Redis 数据库** ```java @SpringBootTest class RedisApplicationTests { @Autowired @Qualifier("stuRedisTemplate") private RedisTemplate<String, Student> stuRedisTemplate; @Test public void redisTest3() { Student student = new Student(99, "王五", 24); stuRedisTemplate.opsForValue().set("student02", student); Student student2 = stuRedisTemplate.opsForValue().get("student02"); System.out.println(student2); ///Student(id=99, name=王五, age=24) } } ``` :-: ![](https://img.kancloud.cn/22/52/225232f63b8cb1d3a598d9adcf9b2fea_1763x439.png) 保存到 Redis 的 JSON 字符串