博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Protostuff 序列化
阅读量:7099 次
发布时间:2019-06-28

本文共 2447 字,大约阅读时间需要 8 分钟。

hot3.png

protostuff 是简化protobuf开发的java的操作工具jar 。

先看看 protobuf 的使用流程:

1.先编写proto文件格式,例如

message Person {    required int32 id = 1;    required string name = 2;    optional string email = 3;  }

2.运行编译程序,生成实体类Person.java

protoc  --java_out=./src   ./person.proto
3.在程序中可以直接使用Person类的相关函数进行序列化和反序列化

//序列化  Person person = builder.build();  byte[] buf = person.toByteArray();  //反序列化  Person person2 = PersonProbuf.Person.parseFrom(buf);

上面的流程看似很方便了,有什么问题呢?还能不能再改进呢?我们先看看生成的Person类代码吧,竟然有几千行。

实际上我们只是包含了3个变量而已,可读性大大降低了。其次,开发过程每次都得借助外部的编译工具来生成代码。

如果采用上面的 protobuf ,需要先编写proto文件,然后通过protoc进行编译,将生成的代码引入到我们java工程中,如果我们采用protostuff的形式,我们可以免去上面的过程,具体如下:

protostuff 使用流程:

1、加入maven依赖:

    
com.dyuproject.protostuff
    
protostuff-runtime
    
1.0.8
    
com.dyuproject.protostuff
    
protostuff-core
    
1.0.8

2、定义一个User的bean:

public class User {    private String name ;    private String password;    private Long age ;    public User() {    }    public User(String name, String password, Long age) {        this.name = name;        this.password = password;        this.age = age;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    public Long getAge() {        return age;    }    public void setAge(Long age) {        this.age = age;    }    @Override    public String toString() {        return "User{" +                "name='" + name + '\'' +                ", password='" + password + '\'' +                ", age=" + age +                '}';    }}

3、测试使用:

public class ProtostuffTest {    public static void main(String[] args) {        // new User instance        User user = new User("name", "passoword", 12L);        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);        Schema
 schema = RuntimeSchema.createFrom(User.class);        // 序列化 user 类        byte[] bytes = ProtostuffIOUtil.toByteArray(user, schema, buffer);        User t = new User();        // 将 bytes 反序列化 , 存储到 t 变量里面        ProtostuffIOUtil.mergeFrom(bytes, t, schema);        System.out.println("反序列化结果:" + t);    }}

说明:

这里只是一个简单的例子,别的可以去官网学习:

转载于:https://my.oschina.net/u/725800/blog/530415

你可能感兴趣的文章
在Azure Cloud Service中部署Java Web App(2)
查看>>
nodejs递归创建多层目录
查看>>
SCCM2012操作系统部署OSD补充
查看>>
rz sz 安装使用
查看>>
MySQL my.cnf参数配置优化详解
查看>>
php读取ACCESS数据库时,内容被截断的原因和解决
查看>>
#pragma指令
查看>>
FreeBSD使用
查看>>
电子书平台不应有裁判权
查看>>
XQuery:连通SQL与NoSQL的良好桥梁
查看>>
Trie树
查看>>
UVA 11389——The Bus Driver Problem
查看>>
黑白图像(DFS)
查看>>
RFID与智能卡
查看>>
Ubuntu16.04架设最新版本SSH2开发框架(maven构建)
查看>>
CentOS 7 的初始化
查看>>
Hibernate 一对一双向关联 Annotation
查看>>
常见邮件服务器(接收服务器和发送邮件服务器)地址
查看>>
th:text/th:utext属性
查看>>
ID生成策略之Annotation的三个方式
查看>>