本文主要是介绍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;
}
}
这篇关于protostuff使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!