protostuff使用


之前使用redis存储pojo时从未想过实例化,只是转成hashes处理起来不方便取的时候也麻烦,用了序列化方便多了!


import com.dyuproject.protostuff.LinkedBuffer;

import com.dyuproject.protostuff.ProtostuffIOUtil;

import com.dyuproject.protostuff.runtime.RuntimeSchema;

import com.netease.seckill.entity.Seckill;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;

import redis.clients.jedis.JedisPool;


public class RedisTest {


private Logger logger = LoggerFactory.getLogger(this.getClass());

private JedisPool jedisPool;

private int port;

private String ip;

public RedisDao(String ip, int port) {

logger.info("---------------------------------ip:{},port:{}",ip,port);

this.port = port;

this.ip = ip;

}


//Serialize function

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


public User getUser(int id) {

jedisPool = new JedisPool(ip, port);

//redis operate

try {

Jedis jedis = jedisPool.getResource();

try {

String key = "User:" + id;

//由于redis内部没有实现序列化方法,而且jdk自带的implaments Serializable比较慢,会影响并发,因此需要使用第三方序列化方法.

byte[] bytes = jedis.get(key.getBytes());

if(null != bytes){

User user = schema.newMessage();

ProtostuffIOUtil.mergeFrom(bytes,user,schema);

//reSerialize

return user;

}

} finally {

jedisPool.close();

}

} catch (Exception e) {

logger.error(e.getMessage(),e);

}


return null;

}


public String putUser(User user) {

jedisPool = new JedisPool(ip, port);

//set Object(user) ->Serialize -> byte[]

try{

Jedis jedis = jedisPool.getResource();

try{

String key = "User:"+user.getId();

byte[] bytes = ProtostuffIOUtil.toByteArray(user, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));

//time out  cache

int timeout = 60*60;

String result = jedis.setex(key.getBytes(),timeout,bytes);

return result;

}finally {

jedisPool.close();

}

}catch (Exception e){

logger.error(e.getMessage(),e);

}

return null;

}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值