jedis这么序列化和反序列化

下面就是代码,麻烦大师解读一下啊,太难了

private Logger logger = LoggerFactory.getLogger(this.getClass());
private final JedisPool jedisPool;  //类似数据库连接池
private RuntimeSchema<Seckill> schema = RuntimeSchema.createFrom(Seckill.class);

public RedisDao(String ip, int port) {
   jedisPool = new JedisPool(ip, port);
}

public Seckill getSeckill(long seckillId) {
   //redis操作逻辑
   try {
       Jedis jedis = jedisPool.getResource();
       try {
           String key = "seckill: " + seckillId;
           byte[] bytes = jedis.get(key.getBytes());
           if (bytes != null) {
               Seckill seckill = schema.newMessage();  //创建空对象
               ProtobufIOUtil.mergeFrom(bytes, seckill, schema);
               //seckill被反序列化
               return seckill;
           }
       } finally {
           jedis.close();
       }
   } catch (Exception e) {
       logger.error(e.getMessage(), e);
   }
   return null;
}

public String putSeckill(Seckill seckill) {
   //set Object(Seckill) --> 序列化 --> byte[]
   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 {
           jedis.close();
       }
   } catch (Exception e) {
       logger.error(e.getMessage(), e);
   }
   return null;
}

fenkapian
浏览 2189回答 0
0回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java