1. 程式人生 > >java Redis快取加protostuff反序列例項

java Redis快取加protostuff反序列例項

好處:使用Redis提高程式碼的執行速度,比每次都從資料庫中獲取快,protostuff反序列比java 自身的反序列的速度更快

一、需要現在電腦安裝redio

二、工程中需要匯入的jar的包

     1、jedis-2.7.3.jar(支援redis)

     2、commons-pool2-2.0.jar(支援redis)

     3、protostuff-api-1.0.8.jar(支援protostuff)

     4、protostuff-collectionschema-1.0.8.jar(支援protostuff,別忘這個jar,不然執行時會出錯)

     5、protostuff-core-1.0.8.jar(支援protostuff)

     6、protostuff-runtime-1.0.8.jar(支援protostuff)

    注意:若出現java.lang.ClassNotFoundException: com.dyuproject.protostuff.MapSchema$MessageFactory 錯誤,是因為沒有將以上的jar包完全匯入,執行時找不到對應的類

三、程式碼

    1. RedisDao.jav(由於Redis是關於資料庫的資料快取的,所以應該歸為DAO層)

package org.ssm.dao.cache;

import org.ssm.entity.Seckill;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtobufIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;


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);

//獲取redis中的物件
public Seckill getSeckill(long seckillId){

try {
Jedis jedis = jedisPool.getResource();
try {
String key = "seckill:"+seckillId;
//並沒有實現內部序列化操作
//get -> byte[] -> 反序列 -> Object(seckill)
//採用自定義序列化
byte[] bytes = jedis.get(key.getBytes());
if(bytes != null){
//空物件
Seckill seckill = schema.newMessage();
ProtobufIOUtil.mergeFrom(bytes, seckill, schema);
//seckill 反序列化
return seckill;
}
} finally {
// TODO: handle exception
jedis.close();
}
} catch (Exception e) {
// TODO: handle exception
}

return null;
}

//向redis中儲存物件
public String putSeckill(Seckill seckill){
try {
Jedis jedis = jedisPool.getResource();
try {
String key = "seckill:"+seckill.getSeckillId();
byte[] bytes = ProtobufIOUtil.toByteArray(seckill, schema, 
LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
int timeOut = 60*60;//一個小時
String result = jedis.setex(key.getBytes(), timeOut, bytes);
return result;

} finally {
// TODO: handle exception
jedis.close();
}
} catch (Exception e) {
// TODO: handle exception
}
return null;
}


}

注意:如果redis是在本機安裝,需要開啟redis,並且dos介面不能關閉,才能獲取到redis 快取中的物件