1. 程式人生 > >Protostuff 序列化和反序列化工具

Protostuff 序列化和反序列化工具

google 原生的Protobuf用起來非常麻煩,需要編寫.proto ,然後又要編譯成.proto檔案,生成對應的java檔案,但是速度是上又是相當可觀的,在專案中設計對序列化工具進行調優,就看見了一篇《java序列化/反序列化之xstream、protobuf、protostuff 的比較與使用例子》
發現 Protostuff 便捷,簡單, very nice !

在maven 專案pom 中加入

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

編寫序列化工具類:

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtobufIOUtil;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;

/**
 * 序列化and反序列化工具
 * @author Lilu
 *
 */
public class ProtoBufUtil {

    public
ProtoBufUtil(){ super(); } @SuppressWarnings("unchecked") public static <T> byte[] Serializable(T o){ Schema schema =RuntimeSchema.getSchema(o.getClass()); return ProtobufIOUtil.toByteArray(o, schema, LinkedBuffer.allocate(256)); } @SuppressWarnings("unchecked") public static <T> T deserializer(byte[] bytes, Class<T> clazz) { T obj = null; try { obj = clazz.newInstance(); Schema schema = RuntimeSchema.getSchema(obj.getClass()); ProtostuffIOUtil.mergeFrom(bytes, obj, schema); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return obj; } }

接下來編寫好我們的模型類:

public class Model {

    private String name;

    private int age;

    private String type;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "Model [name=" + name + ", age=" + age + ", type=" + type + "]";
    }   
}

測試程式碼:

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {

        Model model = new Model();
        model.setName("jack");
        model.setAge(22);
        model.setType("學生");

        byte[] serializable = ProtoBufUtil.Serializable(model);
        System.out.println("serializable : "+Arrays.toString(serializable));

        Model deserializer = ProtoBufUtil.deserializer(serializable, Model.class);
        System.out.println("deserializer : "+deserializer.toString());
    }
}

輸出結果:

serializable : [10, 4, 106, 97, 99, 107, 16, 22, 26, 6, -27, -83, -90, -25, -108, -97]
deserializer : Model [name=jack, age=22, type=學生]

總結:
當檔案較小的時候就可以採用java 自帶的Serializable工具,這樣會快一些。。