当前位置: 首页 > news >正文

自定义RedisTemplate序列化器

大纲

  • RedisSerializer
  • FastJsonRedisSerializer
  • 自定义二进制序列化器
  • 总结
  • 代码

在《RedisTemplate保存二进制数据的方法》一文中,我们将Java对象通过《使用java.io库序列化Java对象》中介绍的方法转换为二进制数组,然后保存到Redis中。实际可以通过定制RedisTemplate序列化器来避开手工序列化和反序列化的工作。本文我们将介绍3种常见的序列化器。

RedisSerializer

package org.example.redistemplateexample.config;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;@Configuration
public class RedisTemplateBeansConfig {@Bean(name = "nomaljsonRedisTemplate")public <T> RedisTemplate<String, T> nomaljsonRedisTemplate(RedisConnectionFactory connectionFactory) {RedisTemplate<String, T> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(connectionFactory);redisTemplate.setValueSerializer(RedisSerializer.json());redisTemplate.setHashValueSerializer(RedisSerializer.json());redisTemplate.setKeySerializer(RedisSerializer.string());redisTemplate.setHashKeySerializer(RedisSerializer.string());redisTemplate.afterPropertiesSet();return redisTemplate;}
}

主要设置ValueSerializer和HashValueSerializer。RedisSerializer.json()会将模板类型T的对象序列化为Json,然后保存到Redis中。
然后定义一个操作类,并使用上面创建的名字为nomaljsonRedisTemplate的redisTemplate。

package org.example.redistemplateexample.redis;import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;import jakarta.annotation.Resource;@Component
public class NomalJsonOperation<T> {@Resource(name = "nomaljsonRedisTemplate")public RedisTemplate<String, T> redisTemplate;public void Set(String key, T value) {redisTemplate.opsForValue().set(key, value);}public T Get(String key) {return redisTemplate.opsForValue().get(key);}
}

测试代码如下

package org.example.redistemplateexample.redis;import org.example.redistemplateexample.pojo.BaseTypes;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
public class NomalJsonOperationTest {@Autowiredprivate NomalJsonOperation<BaseTypes> nomalJsonOperation;@Testpublic void testSetGet() {String key = "NomalJsonOperationTest";BaseTypes value = generate(2);nomalJsonOperation.Set(key, value);BaseTypes result = nomalJsonOperation.Get(key);assertEquals(value, result);}private BaseTypes generate(int mark) {BaseTypes baseTypes = new BaseTypes();baseTypes.setByteValue((byte) mark);baseTypes.setShortValue((short) mark);baseTypes.setIntValue(mark);baseTypes.setLongValue((long) mark);baseTypes.setFloatValue((float) mark);baseTypes.setDoubleValue((double) mark);baseTypes.setCharValue((char) mark);baseTypes.setBooleanValue(mark % 2 == 0);return baseTypes;}
}

在这里插入图片描述

FastJsonRedisSerializer

fastjson是阿里巴巴公司推出的json序列化库,在现实生产中广泛应用。
但是在我们的场景下,使用fastjson需要做一些特殊处理,模式也和其他两者不一样。

package org.example.redistemplateexample.config;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 com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;@Configuration
public class RedisTemplateBeansConfig {@Bean(name = "fastjsonRedisTemplate")public RedisTemplate<String, Object> fastjsonRedisTemplate(RedisConnectionFactory connectionFactory) {RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(connectionFactory);redisTemplate.setValueSerializer(new FastJsonRedisSerializer(Object.class));redisTemplate.setHashValueSerializer(new FastJsonRedisSerializer(Object.class));redisTemplate.setKeySerializer(RedisSerializer.string());redisTemplate.setHashKeySerializer(RedisSerializer.string());redisTemplate.afterPropertiesSet();return redisTemplate;}
}

可以看到,我们需要使用RedisTemplate<String, Object>,即模板类的第二类名需要使用Object。这是因为FastJsonRedisSerializer的构造需要指定Class<T>,而我们又不能通过函数的返回值类型T推导出Class<T>,所以只能使用Object.class这种通用的类型。当然,如果不需要使用模板类型,即让RedisTemplate只支持某个特定类型的Value,则可以直接指定确定的类型,而不用使用Object。
相对应的操作类,Get方法也只能返回Object,而不是模板类型T。

package org.example.redistemplateexample.redis;import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;import jakarta.annotation.Resource;@Component
public class FastJsonOperation<T>  {@Resource(name = "fastjsonRedisTemplate")public RedisTemplate<String, T> redisTemplate;public void Set(String key, T value) {redisTemplate.opsForValue().set(key, value);}public Object Get(String key) {return redisTemplate.opsForValue().get(key);}
}

测试的代码如下

package org.example.redistemplateexample.redis;import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.example.redistemplateexample.pojo.BaseTypes;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
public class FastJsonOperationTest {@Autowiredprivate FastJsonOperation<BaseTypes> fastJsonOperation;@Testpublic void testSetGet() {String key = "FastJsonOperationTest";BaseTypes value = generate(2);fastJsonOperation.Set(key, value);BaseTypes result = JSONObject.parseObject(JSON.toJSONString(fastJsonOperation.Get(key)), BaseTypes.class);assertEquals(value, result);}private BaseTypes generate(int mark) {BaseTypes baseTypes = new BaseTypes();baseTypes.setByteValue((byte) mark);baseTypes.setShortValue((short) mark);baseTypes.setIntValue(mark);baseTypes.setLongValue((long) mark);baseTypes.setFloatValue((float) mark);baseTypes.setDoubleValue((double) mark);baseTypes.setCharValue((char) mark);baseTypes.setBooleanValue(mark % 2 == 0);return baseTypes;}
}

我们需要使用JSON.toJSONString将Fastjson序列化后的object转换成Json字符串,然后再使用JSONObject.parseObject将其转化成明确的类型BaseTypes。
这种转换让Fastjson方案黯然失色。
在这里插入图片描述

自定义二进制序列化器

最后我们介绍结合了《使用java.io库序列化Java对象》和《RedisTemplate保存二进制数据的方法》的方式。
首先定义序列化器IoSerializer,它继承于RedisSerializer。中间的序列化和反序列化步骤已经在《使用java.io库序列化Java对象》中有过介绍。

package org.example.redistemplateexample.config;import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;public class IoSerializer<T> implements RedisSerializer<T> {@Overridepublic byte[] serialize(T obj) throws SerializationException {if (obj == null) {return new byte[0];}ByteArrayOutputStream bos = new ByteArrayOutputStream();try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {oos.writeObject(obj);return bos.toByteArray();} catch (Exception e) {throw new SerializationException("Failed to serialize", e);}}@Overridepublic T deserialize(byte[] bytes) throws SerializationException {if (bytes == null || bytes.length == 0) {return null;}ByteArrayInputStream bis = new ByteArrayInputStream(bytes);try( ObjectInputStream ois = new ObjectInputStream(bis)) {T obj = (T) ois.readObject();return obj;} catch (Exception e) {throw new SerializationException("Failed to deserialize", e);}}
}

然后设置序列化器

package org.example.redistemplateexample.config;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;@Configuration
public class RedisTemplateBeansConfig {@Bean(name = "iomemoryRedisTemplate")public <T> RedisTemplate<String, T> iomemoryRedisTemplate(RedisConnectionFactory connectionFactory) {RedisTemplate<String, T> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(connectionFactory);redisTemplate.setValueSerializer(new IoSerializer<T>());redisTemplate.setHashValueSerializer(new IoSerializer<T>());redisTemplate.setKeySerializer(RedisSerializer.string());redisTemplate.setHashKeySerializer(RedisSerializer.string());redisTemplate.afterPropertiesSet();return redisTemplate;}
}

再定义个操作类

package org.example.redistemplateexample.redis;import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;import jakarta.annotation.Resource;@Component
public class IoMemoryOperation<T> {@Resource(name = "iomemoryRedisTemplate")public RedisTemplate<String, T> redisTemplate;public void Set(String key, T value) {redisTemplate.opsForValue().set(key, value);}public T Get(String key) {return redisTemplate.opsForValue().get(key);}
}

测试代码如下

package org.example.redistemplateexample.redis;import org.example.redistemplateexample.pojo.BaseTypes;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
public class IoMemoryOperationTest {@Autowiredprivate IoMemoryOperation<BaseTypes> ioMemoryOperation;@Testpublic void testSetGet() {String key = "IoMemoryOperationTest";BaseTypes value = generate(2);ioMemoryOperation.Set(key, value);BaseTypes result = ioMemoryOperation.Get(key);assertEquals(value, result);}private BaseTypes generate(int mark) {BaseTypes baseTypes = new BaseTypes();baseTypes.setByteValue((byte) mark);baseTypes.setShortValue((short) mark);baseTypes.setIntValue(mark);baseTypes.setLongValue((long) mark);baseTypes.setFloatValue((float) mark);baseTypes.setDoubleValue((double) mark);baseTypes.setCharValue((char) mark);baseTypes.setBooleanValue(mark % 2 == 0);return baseTypes;}
}

在这里插入图片描述

总结

  • 广泛使用的Fastjson在使用模板类时,类型转换比较丑陋。
  • iomemoryRedisTemplate和nomaljsonRedisTemplate被限制在Java工程中。特别是iomemoryRedisTemplate方案,因为它保存的是Java对象的二进制值。

代码

https://github.com/f304646673/RedisTemplateExample

相关文章:

  • SQL面试题练习 —— 波峰波谷
  • 蛮力法0/1背包问题实验
  • Python 渗透测试:Redis 数据库 弱密码测试.(6379端口)
  • python-数据分析与可视化基础
  • 已有yarn集群部署spark
  • hot100 -- 回溯(上)
  • 利用Python去除PDF水印
  • 前端基础入门三大核心之HTML篇:深入理解重绘与重排 —— 概念、区别与实战演练
  • vue 纵向滚动菜单, 点击滚动到选中菜单
  • 【项目托管git】本地项目托管到 Gitee
  • 机器学习-决策树算法
  • IDEA连接MySQL后如何管理数据库
  • JavaSE——类和对象(二)~~封装
  • 光耦合器的特性和应用概述
  • Mac电脑太卡了怎么办 Mac电脑常见问题 cleanmymacX有必要买吗
  • [nginx文档翻译系列] 控制nginx
  • 【译】React性能工程(下) -- 深入研究React性能调试
  • Android 架构优化~MVP 架构改造
  • css属性的继承、初识值、计算值、当前值、应用值
  • go语言学习初探(一)
  • Java比较器对数组,集合排序
  • Laravel深入学习6 - 应用体系结构:解耦事件处理器
  • learning koa2.x
  • mysql innodb 索引使用指南
  • nodejs:开发并发布一个nodejs包
  • Yeoman_Bower_Grunt
  • 关于Android中设置闹钟的相对比较完善的解决方案
  • 模仿 Go Sort 排序接口实现的自定义排序
  • 使用API自动生成工具优化前端工作流
  • 无服务器化是企业 IT 架构的未来吗?
  • 学习笔记:对象,原型和继承(1)
  • postgresql行列转换函数
  • ​​​​​​​​​​​​​​Γ函数
  • ​zookeeper集群配置与启动
  • ​直流电和交流电有什么区别为什么这个时候又要变成直流电呢?交流转换到直流(整流器)直流变交流(逆变器)​
  • #!/usr/bin/python与#!/usr/bin/env python的区别
  • #HarmonyOS:软件安装window和mac预览Hello World
  • #Spring-boot高级
  • (12)Hive调优——count distinct去重优化
  • (2)leetcode 234.回文链表 141.环形链表
  • (C#)一个最简单的链表类
  • (PySpark)RDD实验实战——取一个数组的中间值
  • (八)光盘的挂载与解挂、挂载CentOS镜像、rpm安装软件详细学习笔记
  • (附源码)ssm教师工作量核算统计系统 毕业设计 162307
  • (附源码)计算机毕业设计ssm-Java网名推荐系统
  • (含react-draggable库以及相关BUG如何解决)固定在左上方某盒子内(如按钮)添加可拖动功能,使用react hook语法实现
  • (提供数据集下载)基于大语言模型LangChain与ChatGLM3-6B本地知识库调优:数据集优化、参数调整、Prompt提示词优化实战
  • (限时免费)震惊!流落人间的haproxy宝典被找到了!一切玄妙尽在此处!
  • (一) springboot详细介绍
  • (转)fock函数详解
  • (转载)(官方)UE4--图像编程----着色器开发
  • (自用)交互协议设计——protobuf序列化
  • .net core docker部署教程和细节问题
  • .NET Core WebAPI中使用swagger版本控制,添加注释
  • .NET DevOps 接入指南 | 1. GitLab 安装