protocol buffer 3 (Protobuf3) ( java 版本 ) 使用入门

概述

proto3 是 google protocol buffer 的新版本。

Protobuf3 应用相当广泛,而且性能优秀,是序列化和网络传输及存储的优秀选择。

官方测试数据:
在这里插入图片描述
在这里插入图片描述

本文只是讲述其简单搭建使用,具体语法请参见官方文档或者其中文翻译

windows安装使用Protobuf3

我这里使用最新的protoc-3.9.0-win64.zip 版本protoc-3.9.0-win64.zip。下载地址:https://github.com/protocolbuffers/protobuf/releases/tag/v3.9.0

将其解压,然后将...\protoc-3.9.0-win64\bin添加到环境变量,使得可以在任何位置使用protoc命令。

mac安装使用Protobuf3

编写第一个protobuf程序

syntax = "proto3";

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

使用命令protoc --java_out . demo1.proto编译成java语言:生成Demo1.java
在这里插入图片描述
将其拷贝到IDE中,编写测试代码

@Test
public void writeObj() throws Exception {
    Demo1.Person person = Demo1.Person.newBuilder().setId(1).setEmail("a.163.com").setName("小明").build();
    person.writeTo(new FileOutputStream("d:/prototbuf.data"));
}

@Test
public void readObj() throws Exception {
    Demo1.Person person = Demo1.Person.parseFrom(new FileInputStream("d:/prototbuf.data"));
    System.out.println(String.format("id=%s  name=%s  email=%s", person.getId(), person.getName(), person.getEmail()));
}

当然想要执行,需要引入相关依赖

<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java</artifactId>
    <version>3.9.0</version>
</dependency>

writeObj方法将序列化结构输出到d:/prototbuf.data文件中。可以到D盘打开这个文件看一下,由于是二进制存储,打开会是乱码,不过还是可以看到我们设置的数据
在这里插入图片描述
执行readObj方法,读取序列化后的文件:
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

快乐崇拜234

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值