多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
RedisTemplate 默认使用的序列化机制为 JdkSerializationRedisSerializer,序列化后的值一般如下图。 ![](https://img.kancloud.cn/14/df/14dfe8e5f2e79e1a6860ee7fb80c83a5_2073x276.png) <br/> 我们可以自定义序列化机制,比如将对象序列化为 JSON 字符串。步骤如下: **1. 配置类中自定义RedisTemplate模板** ```java @Configuration public class CustomRedisConfig { @Bean("stuRedisTemplate") public RedisTemplate<Object, Student> stuRedisTemplate(RedisConnectionFactory factory) throws UnknownHostException { RedisTemplate<Object, Student> template = new RedisTemplate<>(); template.setConnectionFactory(factory); //采用JSON的序列化机制 Jackson2JsonRedisSerializer<Student> ser = new Jackson2JsonRedisSerializer<>(Student.class); template.setDefaultSerializer(ser); return template; } } ``` **2. 使用自定义的模板类操作Redis数据库** ```java @RunWith(SpringRunner.class) @SpringBootTest public class Redis01ApplicationTests { @Autowired @Qualifier("stuRedisTemplate") private RedisTemplate<Object, Student> stuRedisTemplate; @Test public void test03() { Student student1 = new Student(200, "张三", 25); stuRedisTemplate.opsForValue().set("stu-02", student1); Student student2 = (Student) stuRedisTemplate.opsForValue().get("stu-02"); System.out.println(student2); //Student(id=200, name=张三, age=25) } } ``` **3. 保存到Redis数据库的JSON字符串** ![](https://img.kancloud.cn/47/1e/471ee9136b87e583481004d5ef027705_1886x373.png)