1. 默认JDK序列化测试
查看源代码:
Redis默认使用JDK的序列化规则:
连接上Redis后,传入对象进行测试:
Employee是一个实体类,包括id、lastName、email、gender等属性。
关于连接Redis等配置,就里就不过多阐述。。。
博主的操作环境是再SpringBoot:
如果需要下载测试代码:https://github.com/GYT0313/SpringBoot-Learning/tree/master/spring-boot-cache
测试代码:
运行,查看Redis数据库:
2. 改写为Json格式
首先需要配置我们自己的Redis序列化规则:
通过查看Redis的自动配置源代码,只需要在我们的自动配置中模仿即可:
创建我们自己的配置:
package com.gyt.springbootcache.config;
import com.gyt.springbootcache.bean.Employee;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
@Configuration
public class MyRedisConfig {
@Bean
public RedisTemplate<Object, Employee> empRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Employee> template = new RedisTemplate<Object, Employee>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
template.setDefaultSerializer(ser);
return template;
}
}
再次测试:
运行查看结果: