将实体类以json格式存入redis
1. 实体类实现Serializable接口
public class Employee implements Serializable {
private Integer id;
private String lastName;
private String email;
private Integer gender; //性别 1男 0女
private Integer dId;
2.编写redis配置类,修改默认序列化方法
新建config.MyReidsConfig.java
@Configuration //标注配置类
public class MyRedisConfig {
@Bean //加入ioc容器
public RedisTemplate<Object, Employee> empRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Employee> template = new RedisTemplate();
Jackson2JsonRedisSerializer<Employee> employeeJackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
template.setDefaultSerializer(employeeJackson2JsonRedisSerializer);
template.setConnectionFactory(redisConnectionFactory);
return template;
}
// 还可以添加其他实体类的序列化方法
@Bean
public RedisTemplate<Object, DepartMent> depRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, DepartMent> template = new RedisTemplate();
Jackson2JsonRedisSerializer<DepartMent> employeeJackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<DepartMent>(DepartMent.class);
template.setDefaultSerializer(employeeJackson2JsonRedisSerializer);
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
3.使用配置好的序列化方法
@Autowired
RedisTemplate<Object,Employee> empRedisTemplate;
@Test
public void redisTest2(){
Employee empById = employeeMapper.getEmpById(1);
// 默认如果保存对象,使用jdk序列化机制,序列化后的数据保存到啊redis中
// redisTemplate.opsForValue().set("emp-01",empById);
//1.将数据以json的方式保存
// 1).使用json转换包,转换以后再存入redis
// 2).redisTemplate默认的序列化规则 编写配置类MyRedisConfig
empRedisTemplate.opsForValue().set("emp-01",empById);
}```