对于系统默认的RedisTemplate默认采用的是JDK的序列化机制,假如我们不希望实用JDK的序列化,可以采用的定制RedisTemplate,并采用自己指定的的序列化方式,例如:
package com.jt.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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;
import org.springframework.data.redis.serializer.RedisSerializer;
import java.net.UnknownHostException;
@Configuration
public class RedisConfig {
//自定义json序列化
public RedisSerializer jsonSerializer(){
//1.定义Redis序列化,反序列化规范对象(此对象底层通过ObjectMapper完成对象序列化和反序列化)
Jackson2JsonRedisSerializer serializer=
new Jackson2JsonRedisSerializer(Object.class);
//2.创建ObjectMapper(有jackson api库提供)对象,基于此对象进行序列化和反序列化
//2.1创建ObjectMapper对象
ObjectMapper objectMapper=new ObjectMapper();
//2.2设置按哪些方法规则进行序列化
objectMapper.setVisibility(PropertyAccessor.GETTER,//get方法
JsonAutoDetect.Visibility.ANY);//Any 表示任意方法访问修饰符
//对象属性值为null的时候不进行序列化存储
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//2.2激活序列化类型存储,对象序列化时还会将对象的类型存储到redis数据库
//假如没有这个配置,redis存储数据时不存储类型,反序列化时会默认将其数据存储到map
objectMapper.activateDefaultTyping(
objectMapper.getPolymorphicTypevalidator(),
ObjectMapper.DefaultTyping.NON_FINAL,//激活序列化类型存储
JsonTypeInfo.As.PROPERTY);//PROPERTY 表示类型会以json对象的形式存储
serializer.setObjectMapper(objectMapper);
return serializer;
}
@Bean
public RedisTemplate
创建Blog对象,然后基于RedisTemplate进行序列化实践,Blog代码如下:
package com.jt.pojo;
import java.io.Serializable;
public class Blog implements Serializable {
private static final long serialVersionUID = -5619615150594284572L;
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Blog{" +
"id=" + id +
", title='" + name + ''' +
'}';
}
}
在RedisTemplateTests类中添加如下单元测试方法,进行测试,例如:
@Test
void test02(){
// redisTemplate.setKeySerializer(RedisSerializer.string());
// redisTemplate.setValueSerializer(RedisSerializer.json());
//获取blog操作对象
ValueOperations ops = redisTemplate.opsForValue();
//2.执行Blog对象读写操作
Blog blog = new Blog();
blog.setId(10L);
blog.setName("redis01");
ops.set("blog",blog);
blog = (Blog) ops.get("blog");//反序列化
System.out.println(blog);
}



