一款简单又好用的序列化工具-Protostuff,及配合Jedis的使用

之前我们谈到使用Jedis存储数据时,需要先进行序列化,[RedisTemplate和Jedis的区别],那么现在我们就来介绍一款非常好用的序列化工具-protostuff,然后再讲讲它如何配合Jedis进行使用
话不多说,直接上代码,首先看看它如何使用:

首先还是要引入依赖

<dependency>
    <groupId>com.dyuproject.protostuff</groupId>
    <artifactId>protostuff-runtime</artifactId>
    <version>1.1.5</version>
</dependency>
<dependency>
    <groupId>com.dyuproject.protostuff</groupId>
    <artifactId>protostuff-core</artifactId>
    <version>1.1.5</version>
</dependency>

然后就可以进行使用

//定义一个Demo类
class Demo{
    int value;
    //此处省略构造函数和get,set函数
 }
 
class ProtostuffUtil {
   //进行序列化,以demo对象作为参数
    public static byte[] serialize(Demo demo){
        RuntimeSchema<Demo> schema = RuntimeSchema.createFrom(Demo.class);
        byte[] bytes = null;
            try{
                bytes = ProtostuffIOUtil.toByteArray(demo,schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
            }catch (Exception e) {
                throw new RuntimeException("serialize exception");
            }
        return bytes;
    }
    //进行反序列化
    public static Demo deSerialize(byte[] bytes,Demo demo){
        RuntimeSchema<Demo> schema = RuntimeSchema.createFrom(Demo.class);
        try{
            demo = schema.newMessage();
            ProtostuffIOUtil.mergeFrom(bytes,demo,schema);
            return demo;
        }catch (Exception e) {
            throw new RuntimeException("serialize exception");
        }
    }
    

配合Jedis进行测试

    public static void main(String[] args){
        Jedis jedis = new Jedis();
        Demo demo = new Demo(3);
        //对demo实例进行序列化
        byte[] bytes = ProtostuffUtil.serialize(demo);
        //将序列化后的demo存入redis
        jedis.set("hello".getBytes(),bytes);
       //利用key得到序列化后的demo实例
       byte[] resByte = jedis.get("hello".getBytes());
       //将demo实例反序列化
       Demo res = ProtostuffUtil.deSerialize(bytes,new Demo());
       System.out.println(res.value);
   }
}
发布了17 篇原创文章 · 获赞 12 · 访问量 8298

猜你喜欢

转载自blog.csdn.net/Sun_Dean/article/details/104071402