目录
场景: 使用springboot自带的redistemplate 连接redis
效果: \xac\xed\x00\x05t\x00\x07auther1
=============> 方法三(高级) <==============
4. 一个类自定义的序列化配置
场景: 使用springboot自带的redistemplate 连接redis
两种 StringRedisTemplate redisTemplate
而 redisTemplate 存储的 是默认的jdk序列化方式
效果: \xac\xed\x00\x05t\x00\x07auther1
@Test
void testString() {
ValueOperations<String, String> value = redisTemplate.opsForValue();
value.set("name","pzy");
value.set("auther","pzyzx",10); //向右偏移10个字符
value.set("auther1","pzyzx", Duration.ofSeconds(10)); //10秒后过期
String name = value.get("name");//\xac\xed\x00\x05t\x00\x07auther1
System.out.println(name);
}
修改 默认的序列化方式
方式一:(源码中可以看到 粘贴到需要的方法内)
//修改序列化方式(自定义) 源码中有
redisTemplate.setKeySerializer(RedisSerializer.string());
redisTemplate.setValueSerializer(RedisSerializer.string());
redisTemplate.setHashKeySerializer(RedisSerializer.string());
redisTemplate.setHashValueSerializer(RedisSerializer.string());
方式二: 写一个配置类(简单)
序列化方式相同
@Configuration
public class RedisConfig {//RedisAutoConfiguration
//简单定制
@Bean
public RedisTemplate<Object, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
//设置key的序列化方式
template.setKeySerializer(RedisSerializer.string());
template.setHashKeySerializer(RedisSerializer.string());
//设置值的序列化方式
template.setValueSerializer(RedisSerializer.json());
template.setHashValueSerializer(RedisSerializer.json());
return template;
}
}
效果(统一)
=============> 方法三(高级) <==============
1. 导入依赖:
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.3</version>
</dependency>
2. 写自定义序列化类
Redis使用FastJson序列化
package cn.pingzhuyan.config;
import java.nio.charset.Charset;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;
public FastJson2JsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException {
if (t == null) {
return new byte[0];
}
return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return JSON.parseObject(str, clazz, JSONReader.Feature.SupportAutoType);
}
}
3. redis的高级序列化配置
package cn.pingzhuyan.config;
/**
* @Author pzy
* @Description: TODO
* @Version 0.1.0
*/
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
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.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
//@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
// @SuppressWarnings(value = {"unchecked", "rawtypes"})
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
// 使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(RedisSerializer.string());
template.setValueSerializer(serializer);
// Hash的key也采用StringRedisSerializer的序列化方式
template.setHashKeySerializer(RedisSerializer.string());
template.setHashValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
}
4. 第二种序列化方式
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.boot.autoconfigure.condition.ConditionalOnMissingBean;
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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import java.net.UnknownHostException;
@Configuration
public class RedisConfig {//RedisAutoConfiguration
//自定义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,//激活序列化类型存储,类不能使用final修饰
JsonTypeInfo.As.PROPERTY);//PROPERTY 表示类型会以json对象属性形式存储
serializer.setObjectMapper(objectMapper);
return serializer;
}
//高级定制
@Bean
public RedisTemplate<Object, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
//设置key的序列化方式
template.setKeySerializer(RedisSerializer.string());
template.setHashKeySerializer(RedisSerializer.string());
//设置值的序列化方式
template.setValueSerializer(jsonSerializer());
template.setHashValueSerializer(jsonSerializer());
//更新一下RedisTemplate对象的默认配置
template.afterPropertiesSet();
return template;
}
}