今天在学习秒杀课程时,看到使用Redis做服务器端的缓存实现更快速的存取,知道redis没有实现内部序列化的操作,所以在处理数据时需要自己执行序列化与反序列化操作。记录下protostuff的使用。
首先引入protostuff的依赖
<!-- protostuff序列化依赖 -->
<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>
Reids存取过程序列化与反序列换操作(Seckill是一个类):
(1) get取数据:
// get -> byte[] -> 反序列化 -> Object(Seckill)
//采用自定义序列化,protostuff转换有get set方法的pojo.
byte[] bytes = jedis.get(key.getBytes());
if(bytes != null) {
//空对象
Seckill seckill = schema.newMessage();
ProtostuffIOUtil.mergeFrom(bytes, seckill, schema);
//seckill被反序列化
return seckill;
}
(2) set存数据
//set Object(Seckill) -> 序列化 -> byte[]
String key = "seckill:" + seckill.getSeckillId();
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;