java Redis缓存加protostuff反序列实例

来源:互联网 发布:江苏域名备案 编辑:程序博客网 时间:2024/05/16 00:53

好处:使用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 缓存中的对象

0 0