Kang Lv3

title: proto文件的编译与序列化
date: 2022-07-18 20:15:41
tags:
- Proto
categories: # 诗和远方|学习笔记|知识分享|利器酷
- 术业专攻
keyword: # 关键词
description: Protobuf的学习与使用 # 文章描述
sticky: 0 # 置顶,数字越大,置頂的优先级越大

一、背景

最近因工作原因,需要请求其他服务,而这个服务POST请求的数据内容是request对象(Protocol Buffer格式)序列化之后的数据。

Protocol Buffers:一种序列化数据的框架,它与平台、语言无关,具有良好的可扩展性。
Portobuf的序列化的结果体积要比XML、JSON小很多,序列化和反序列化速度比XML、JSON快很多。

二、快速开始

1.Protobuf 环境搭建

下载源码并编译
地址:https://github.com/protocolbuffers/protobuf/releases

1
2
3
4
5
6
unzip protobuf.zip 
cd protobuf/
./autogen.sh
./configure
make
make install

编译大约需要20分钟左右,编译成功之后可以使用以下命令验证是否成功

1
protoc --version

2.编写proto文件并进行编译

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
syntax = "proto2";

message Request {
required int32 pageSize = 1 [ default = 0 ];

required int32 pageNum = 2;

}

message Response {
optional int64 video_id = 1;

optional string title = 2;

optional string video_url = 3;
}

1
protoc --java_out=./ -I=./  *.proto

–java_out : 指定输出的 Java 文件所在的目录
-I :指定 proto 文件所在的目录
*.proto : 表示在 -I 指定的目录下查找 以 .proto 文件结尾的文件

应用于业务中

1.引入依赖

1
2
3
4
5
6
7
8
9
10
11
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java-util -->
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java-util</artifactId>
<version>3.7.1</version>
</dependency>

序列化与发送请求

1
2
3
4
5
6
7
8
9
10
11
String API_URl = "url地址";
HttpHeaders headers = new HttpHeaders();
// HTTP header 设置
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
Builder builder = Request.newBuilder();
builder.setPageSize(2);
builder.setPageNum(10);
Request build = builder.build();
byte[] info = build.toByteArray();
HttpEntity<byte[]> request = new HttpEntity<>(info, headers);
ResponseEntity<byte[]> entity = restTemplate.exchange(API_URl, HttpMethod.POST, request, byte[].class);

接收响应与反序列化

1
2
3
ResponseEntity<byte[]> entity = restTemplate.exchange(API_URl, HttpMethod.POST, request, byte[].class);
byte[] body = entity.getBody();
Response response = Response.parseFrom(body);
  • 本文标题:
  • 本文作者:Kang
  • 创建时间:2022-07-19 00:14:00
  • 本文链接:ykhou.github.io2022/07/19/proto文件的编译和序列化/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!