如何在 triple 协议场景下使用 protobuf、json 序列化
本文介绍 protobuf 序列化,如何在 triple 协议场景下使用 protobuf、json 序列化。
1 介绍
Protobuf(Protocol Buffers) 是由 Google 开发的一种轻量级、高效的数据交换格式,它被用于结构化数据的序列化、反序列化和传输。 相比于XML 和JSON 等文本格式,Protobuf 具有更小的数据体积、更快的解析速度和更强的可扩展性。
2 使用方式
在使用 Protobuf(IDL) 开发 triple 通信服务 的时候,dubbo server 将自动启用 protobuf、protobuf-json 序列化模式支持。
2.1 添加依赖
使用 triple + protobuf 模式,必须添加以下依赖:
1. <dependencies>
2. <dependency>
3. <groupId>com.google.protobuf</groupId>
4. <artifactId>protobuf-java</artifactId>
5. <version>3.19.6</version>
6. </dependency>
7. <!-- 提供 protobuf-json 格式请求支持 -->>
8. <dependency>
9. <groupId>com.google.protobuf</groupId>
10. <artifactId>protobuf-java-util</artifactId>
11. <version>3.19.6</version>
12. </dependency>
13. </dependencies>
2.2 配置启用
只要是基于 Protobuf(IDL) 开发模式进行 triple 协议通信 ,就会使用 protobuf 序列化,只要定义 protobuf 文件并启用 triple 协议即可。
当使用 cURL 访问 triple 服务时,是会启用 protobuf-json 序列化模式
1. curl \
2. --header "Content-Type: application/json" \
3. --data '{"name":"Dubbo"}' \
4. http://localhost:50052/org.apache.dubbo.samples.tri.unary.Greeter/greet/
protobuf 服务定义示例:
1. syntax = "proto3";
2. option java_multiple_files = true;
3. package org.apache.dubbo.samples.tri.unary;
5. message GreeterRequest {
6. string name = 1;
7. }
8. message GreeterReply {
9. string message = 1;
10. }
12. service Greeter{
13. rpc greet(GreeterRequest) returns (GreeterReply);
14. }
协议配置:
1. # application.yml (Spring Boot)
2. dubbo:
3. protocol:
4. name: tri
或
1. # dubbo.properties
2. dubbo.protocol.name=tri
或
1. <dubbo:protocol name="tri" />
最后修改 September 13, 2024: Refactor website structure (#2860) (1a4b998f54b)
