序列化+protobuff+redis


背景:

當redis里面需要存儲 “key-字符串,value-對象” 時,是不能直接存對象,而是需要將序列化后的對象存進redis。

redis沒有實現內部序列化對象的功能,所以需要自己提前序列化對象。

序列化介紹:

序列化的方法有很多,比如java原生序列化(需要實現Serializable接口)、json序列化、protobuff序列化。

java原生序列化:https://www.cnblogs.com/yaobolove/p/5632891.html

protobuff序列化:告訴我對象的class,內部有schema來描述你的class是什么結構,class必須有get/set方法這種標准的類,而不是string等類

第一步:maven依賴  
<!--prostuff序列化依賴--> <dependency> <groupId>com.dyuproject.protostuff</groupId> <artifactId>protostuff-core</artifactId> <version>1.0.8</version> </dependency> <dependency> <groupId>com.dyuproject.protostuff</groupId> <artifactId>protostuff-runtime</artifactId> <version>1.0.8</version> </dependency>

第二步:
定義全局的變量,注意Seckill是我自己定義的一個類,不需要實現接口
   private RuntimeSchema<Seckill> schema = RuntimeSchema.createFrom(Seckill.class);

完整代碼:
public class RedisDao {
private final JedisPool jedisPool;

public RedisDao(String ip, int port) {
jedisPool = new JedisPool(ip, port);
}

private RuntimeSchema<Seckill> schema = RuntimeSchema.createFrom(Seckill.class);


public Seckill getSeckill(long seckillId) {
//redis操作邏輯
try {
Jedis jedis = jedisPool.getResource();
try {
String key = "seckill:" + seckillId;
//並沒有實現哪部序列化操作
//采用自定義序列化
//protostuff: pojo.
byte[] bytes = jedis.get(key.getBytes());
//緩存重獲取到
if (bytes != null) {
Seckill seckill=schema.newMessage();//這是一個空對象
ProtostuffIOUtil.mergeFrom(bytes,seckill,schema);//按照schema把bytes傳到空對象里
//seckill被反序列化

return seckill;
}
}finally {
jedis.close();
}
}catch (Exception e) {

}
return null;
}
   public String putSeckill(Seckill seckill) {
try {
Jedis jedis = jedisPool.getResource();
try {
String key = "seckill:" + seckill.getSeckillId();
//LinkedBuffer.allocate是緩存器,當壓縮的對象太大是,起到緩沖的作用,該方法是protobuff自帶的。
byte[] bytes = ProtostuffIOUtil.toByteArray(seckill, schema,
LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
//超時緩存
int timeout = 60 * 60;//1小時
String result = jedis.setex(key.getBytes(),timeout,bytes);

return result;
}finally {
jedis.close();
}
}catch (Exception e) {

}

return null;
}
}

 

java原生序列化:https://www.cnblogs.com/yaobolove/p/5632891.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM