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
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。