介绍redis存储对象的两种方式
redis存储对象的两种方式
最近工作闲来无聊,写写博客打发时间,说到redis存储对象,我有着自己的小实验,来验证两种方式,有兴趣的童鞋可以小读一下。
搭建redis服务端,这就不多说了,简单的不要不要的,这里就不废话了
首先,maven构建项目,pom.xml引入redis客户端和gson依赖包,如下所示:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
然后,引入jedis对象,随便选一个数据库索引号
Jedis jedis = new Jedis(host, port);
jedis.select(1);
最后,两种方式来存储对象格式的数据
1.把对象转成json字符串格式
我这里采用gson来处理对象和字符串之间的相互转换
public static void jsonString(Jedis jedis, Person person) {
String key = UUID.randomUUID().toString().replaceAll("-", "");
//对象转字符串
String value = new Gson().toJson(person);
jedis.set(key, value);
String sValue = jedis.get(key);
//字符串转对象
Person person2 = new Gson().fromJson(Person.class, sValue);
}
在redis的存储情况如下

2.把对象转成字节流格式,也就是序列化和反序列化
先介绍序列化方法
public static byte[] serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try {
//序列化
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
return bytes;
} catch (Exception e) {
}
return null;
}
反序列化
public static Object unserialize(byte[] bytes) {
ByteArrayInputStream bais = null;
try {
//反序列化
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
}
return null;
}
自己简单封装了一个方法做个测试
public static void serializeString(Jedis jedis, Person person) {
byte[] key = UUID.randomUUID().toString().replaceAll("-", "").getBytes();
byte[] value = serialize(person);
jedis.set(key, value);
byte[] sValue = jedis.get(key);
Person person2= (Person) unserialize(sValue);
}
在redis的存储情况如下

最后总结发现,少量数据用第一种方式消耗的时间反而更合适,如果存储数据量超过10W字节,可以考虑第二种方式来提升效率。
谢谢大家。
作者:彼岸花开_7881
链接:https://www.jianshu.com/p/c22954a9c37d
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)