首页 > 其他分享 >【序列化和反序列化】Protostuff

【序列化和反序列化】Protostuff

时间:2022-12-06 16:48:39浏览次数:64  
标签:Protostuff protostuff Score io RuntimeSchema 序列化 schema

一、protostuff介绍

protostuff基于Google protobuf ,但是提供了更多的功能和更简易的用法。其中,protostuff-runtime实现了无需预编译对java bean进行protobuf序列化/反序列化的能力。protostuff-runtime的局限是序列化前需预先传入schema,反序列化不负责对象的创建只负责复制,因此必须提供默认构造函数。在性能上,protostuff不输原生的protobuf,甚至有反超之势

 

二、protostuff用法

maven

<dependency>
      <groupId>io.protostuff</groupId>
      <artifactId>protostuff-core</artifactId>
      <version>1.7.4</version>
</dependency>

<dependency>
      <groupId>io.protostuff</groupId>
      <artifactId>protostuff-runtime</artifactId>
      <version>1.7.4</version>
</dependency>

工具类

package com.chenly.serialize.protostuff;

import com.chenly.serialize.bean.Score;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;;


/**
 * @author: chenly
 * @date: 2022-12-06 14:56
 * @description:
 * @version: 1.0
 */
public class ProtostuffTest2 {

    public static void main(String[] args) {
        Score score = Score.builder()
                .className("一班")
                .stuName("张三").course("生物").score(90).build();
        long startTime = System.currentTimeMillis();
        //序列化
        byte[] bytes = serialize(score,Score.class);
        //反序列化
        Score object = deserialize(bytes,Score.class);
        System.out.println(object);
        System.out.println("耗时:"+(System.currentTimeMillis()-startTime)/1000.00);
    }

    /** 序列化 */
    public static <T> byte[] serialize(T obj,Class<T> cls)
    {
        // this is lazily created and cached by RuntimeSchema
        // so its safe to call RuntimeSchema.getSchema(Foo.class) over and over
        // The getSchema method is also thread-safe
        Schema<T> schema = RuntimeSchema.getSchema(cls);
        // Re-use (manage) this buffer to avoid allocating on every serialization
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);

        //序列化
        byte[] protostuff;
        try{
            protostuff = ProtostuffIOUtil.toByteArray(obj, schema, buffer);
            return protostuff;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally
        {
            buffer.clear();
        }
    }

    /** 反序列化 */
    public static  <T> T deserialize(byte[] bytes,Class<T> cls)
    {
        Schema<T> schema = RuntimeSchema.getSchema(cls);
        // 反序列化
        T obj = schema.newMessage();
        ProtostuffIOUtil.mergeFrom(bytes, obj, schema);
        return obj;
    }

}

 

 

参考地址:https://github.com/protostuff/protostuff

标签:Protostuff,protostuff,Score,io,RuntimeSchema,序列化,schema
From: https://www.cnblogs.com/kiko2014551511/p/16932855.html

相关文章