protobuf 分布式数据模型

优点

  • 多语言共用
  • 方便定义,不需手动创建,直接编译生成
  • 序列化数据更小,序列化时不会带参名,反序列化时通过参数列表排序来赋值

使用

  • 需要在 pom.xml 文件中新增编译器

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    <!-- 方式 1 配置更全 -->
    <plugin>
    <groupId>org.xolstice.maven.plugins</groupId>
    <artifactId>protobuf-maven-plugin</artifactId>
    <version>0.6.1</version>
    <configuration>
    <protocArtifact>com.google.protobuf:protoc:3.7.1:exe:${os.detected.classifier}</protocArtifact>
    <outputDirectory>build/generated/source/proto/main/java</outputDirectory>
    <clearOutputDirectory>false</clearOutputDirectory>
    <protocPlugins>
    <protocPlugin>
    <id>dubbo</id>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo-compiler</artifactId>
    <version>0.0.4.1-SNAPSHOT</version>
    <mainClass>org.apache.dubbo.gen.tri.Dubbo3TripleGenerator</mainClass>
    </protocPlugin>
    </protocPlugins>
    </configuration>
    <executions>
    <execution>
    <goals>
    <goal>compile</goal>
    <goal>test-compile</goal>
    </goals>
    </execution>
    </executions>
    </plugin>

    <!-- 方式 2 -->
    <plugin>
    <groupId>org.xolstice.maven.plugins</groupId>
    <artifactId>protobuf-maven-plugin</artifactId>
    <version>0.6.1</version>
    <configuration>
    <protocArtifact>com.google.protobuf:protoc:3.19.2:exe:${os.detected.classifier}</protocArtifact>
    <pluginId>grpc-java</pluginId>
    <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.45.1:exe:${os.detected.classifier}</pluginArtifact>
    </configuration>
    <executions>
    <execution>
    <goals>
    <goal>compile</goal>
    <goal>compile-custom</goal>
    </goals>
    </execution>
    </executions>
    </plugin>

protobuf 文件格式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
syntax = "proto3";

package com.yyh;

option java_multiple_files = true;
option java_package = "com.yyh";
option java_outer_classname = "UserServiceProto";

service UserService {
rpc GetUser (UserRequest) returns (User) {}
rpc ServerGetUser (UserRequest) returns (stream User) {}
rpc ClientGetUser (stream UserRequest) returns (User) {}
rpc BiGetUser (stream UserRequest) returns (stream User) {}
}

// The response message containing the greetings
message UserRequest {
string uid = 1;
}

// The response message containing the greetings
message User {
string uid = 1; // 排序
string username = 2;
}