在pom.xml加入以下内容: //高速序列化 存储对象 速度是java 实现io 序列化的10倍左右 存储较大的对象时 内置缓存
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>1.0.8</version>
</dependency>
//redis 客户端 jedis 也可以使用别的 推荐
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>1.0.8</version>
//业务层获取jedis 连接池
public RedisDao(String ip,int port) {
// TODO Auto-generated constructor stub
jedisPool= new JedisPool(ip,port);
}
//redis 就是key value 数据库 传入key值获取你所要的对象
//entityclass就是你要序列化的类
//通过key值获取redis中的缓存对象
public T test(String key){
RuntimeSchema<T> schema = RuntimeSchema.createFrom(entityclass);
Jedis jedis = jedisPool.getResource();//获取jedis 对象
byte [] bytes= jedis.get(key.getBytes());
T a =schema.newMessage();
if(bytes!=null){
ProtobufIOUtil.mergeFrom(bytes, a, schema) ;
jedis.close();
return a;
}
return null;
}
//如果该key值中没有对应的对象
//访问数据 返回的对象存入redis中
//LinkedBuffer redis 中缓冲的对象
public void putT(T t){
RuntimeSchema<T> schema = RuntimeSchema.createFrom(entityclass);
//OBJECT -->序列化-->存入redis
Jedis jedis = jedisPool.getResource();
//缓冲对象
byte [] bytes=ProtobufIOUtil.toByteArray(t, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
int timeout = 60 * 60;//缓存的时长 秒为单位
String key = null;
jedis.setex(key.getBytes(), timeout, bytes);
}
来源:oschina
链接:https://my.oschina.net/u/2813558/blog/789237