Skip to content

Latest commit

 

History

History
264 lines (207 loc) · 9.12 KB

3.protobuf_stub_plugin.md

File metadata and controls

264 lines (207 loc) · 9.12 KB

Generating tRPC-Java Stub Code

Stub code is the code used to define the API of the RPC service and its related data formats. tRPC uses protobuf to define the service API and data format, and tRPC-Java provides a Maven plugin to generate Java stub code based on the .proto files that describe the service.

trpc-maven-plugin

Functionality:

  1. Generate tRPC stub code, consisting of two parts:
    1. protobuf data protocol code
    2. tRPC service interface (Java interface)
  2. Generate Validator code (generated by protoc-gen-validate)
  3. Generate a pom.xml file containing the dependencies required for the stub code

Environment Requirements

  • Maven 3.6.3+

Basic Usage

Importing the Maven Plugin

Define the following in the pom.xml file:

<build>
    <plugins>
        <plugin>
            <groupId>com.tencent.trpc</groupId>
            <artifactId>trpc-maven-plugin</artifactId>
            <!-- see version https://github.com/trpc-group/trpc-java/releases -->
            <version>1.0.0</version>
        </plugin>
    </plugins>
</build>

Note that in a multi-module project, the above plugin needs to be imported in the pom.xml file of the child module.

Writing the API Description File (.proto File)

The plugin reads the .proto files directly located in the src/main/proto directory by default. The *.proto files in subdirectories are considered as dependencies. This means that the proto files under src/main/proto/ can import proto files under src/main/proto/{any_sub_dir}. However, it should be noted that relative paths should be used when referencing.

The default proto source file directory can be customized using the protoSourceRoot parameter. See the "Parameter Description" section at the end of the document for details.

Refer to the official documentation for the specific protobuf file syntax. The following uses trpc-java-demo to demonstrate how to use this plugin. The proto file example is as follows:

syntax = "proto3";

package trpc.TestApp.TestServer;

option java_package = "com.tencent.trpc.demo.proto";  // Set the java package of the stub code file
option java_outer_classname = "HelloRequestProtocol"; // Encapsulate multiple protobuf protocol classes into the specified wrapper class

// If do not customize url, no need to import the next proto file.
import "trpc.proto";

// Define data structure

message HelloRequest {
  string message = 1;
}

message HelloResponse {
  string message = 1;
}

// Define API

// Normal service
service GreeterService {
  rpc sayHello (HelloRequest) returns (HelloResponse) {}
}

// Normal service with customized url
service GreeterService2 {
  rpc sayHi (HelloRequest) returns (HelloResponse) {
    option (trpc.alias) = "/api/hi";
  }
}

// Stream service
service StreamGreeterService {
  rpc clientSayHellos (stream HelloRequest) returns (HelloResponse) {}
  rpc serverSayHellos (HelloRequest) returns (stream HelloResponse) {}
  rpc allSayHellos (stream HelloRequest) returns (stream HelloResponse) {}
}

Running the Maven Plugin

The corresponding Maven goal of the plugin is gen-code, which can be used to generate code by running the following command:

// Taking `trpc-java-demo` as an example, execute the code
git clone https://github.com/trpc-group/trpc-java.git
cd trpc-java
mvn -Dmaven.test.skip=true clean install
cd trpc-demo/trpc-java-demo
mvn trpc:gen-code

The plugin goal can also be bound to other Maven phases as needed:

<build>
    <plugins>
        <plugin>
            <groupId>com.tencent.trpc</groupId>
            <artifactId>trpc-maven-plugin</artifactId>
            <version>1.0.0</version>
            <executions>
                <execution>
                    <phase>compile</phase>
                    <goals>
                        <goal>gen-code</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

Collecting the Generated Stub Code

The default output directory of the plugin is target/generated-sources/trpc/java/

The default output directory can be customized using the outputDirectory parameter. See the "Parameter Description" section at the end of the document for details.

Taking the .proto file example from earlier, the generated stub code file structure is as follows:

target/generated-sources/trpc/java/com/tencent/trpc/demo/proto
├── GreeterService2API.java
├── GreeterService2AsyncAPI.java
├── GreeterServiceAPI.java
├── GreeterServiceAsyncAPI.java
├── HelloRequestProtocol.java
├── StreamGreeterServiceAPI.java
├── StreamGreeterServiceAsyncAPI.java
└── StreamGreeterServiceStreamAPI.java

The generated code files contain two types:

  1. tRPC-Java API interface classes, named after the service name in the .proto file + a fixed suffix:
    1. Suffix API.java, representing a regular synchronous API
    2. Suffix AsyncAPI.java, representing an asynchronous API
    3. Suffix StreamAPI.java, representing a streaming API
  2. protobuf protocol classes, which may be a class corresponding to each message defined in the .proto file, or may be wrapped in a single class. The generation of protocol class code is delegated to protoc by the plugin.

Advanced Usage

Defining Interface Aliases

The alias of the tRPC interface can be set by setting the option(trpc.alias) for the RPC in the .proto file:

syntax = "proto3";
...
import "trpc.proto"; // Reference trpc.proto to activate the trpc.alias option, which is built into the trpc-maven-plugin and does not require additional configuration
...
service Greeter {
  rpc SayHello (stream HelloRequest) returns (stream HelloReply) { option(trpc.alias) = "/api/helloworld"; }
}
...

About protoc

The trpc-maven-plugin depends on the protoc executable file to generate protobuf stub code.

Usually, users do not need to worry about this, as the plugin will download the pre-compiled protoc binary file from the Maven remote repository based on the current operating system type.

If the default behavior of the plugin cannot meet your needs (e.g. protoc has not released a pre-compiled binary file for your operating system, or you need a specific version of protoc), the plugin also supports calling the existing protoc executable file in the compilation environment by setting the local protoc command through the plugin parameter <protocExecutable>:

<build>
    <plugins>
        <plugin>
            <groupId>com.tencent.trpc</groupId>
            <artifactId>trpc-maven-plugin</artifactId>
            <version>1.0.0</version> 
            <configuration>
                <protocExecutable>protoc</protocExecutable>
            </configuration>
        </plugin>
    </plugins>
</build>

About Data Validation Code

trpc-maven-plugin supports generating data validation code:

syntax = "proto3";
...
import "validate.proto"; // The required validate.proto is provided by the trpc-maven-plugin and does not require additional configuration
...
message HelloRequest {
  string message = 1 [(validate.rules).string.min_len = 2]; // Define field validation rules
  int64 ts = 2;
}
...

The generation of validation code is implemented by protoc-gen-validate. Similar to the protoc executable file, the plugin automatically downloads the pre-compiled protoc-gen-validate based on the operating system, so usually there is no need to worry about it.

You can also specify the local protoc-gen-validate executable file:

<build>
    <plugins>
        <plugin>
            <groupId>com.tencent.trpc</groupId>
            <artifactId>trpc-maven-plugin</artifactId>
            <version>1.0.0</version>
            <configuration>
                <pgvPluginExecutable>protoc-gen-validate</pgvPluginExecutable>
            </configuration>
        </plugin>
    </plugins>
</build>

Plugin Parameter Description

The plugin's default behavior can be adjusted by changing its parameters.

Parameter list:

Parameter Name Description Default Value
protoSourceRoot .proto source file directory ${basedir}/src/main/proto
outputDirectory Output directory of generated code files ${project.build.directory}/generated-sources/trpc/java
protocExecutable Local protoc executable command null (get pre-compiled file from Maven remote repository)
pgvPluginExecutable Local protoc-gen-validate executable command null (get pre-compiled file from Maven remote repository)
osClassifier Operating system identifier (e.g. linux-x86_64) used to match pre-compiled protoc files Automatically recognized. Setting this parameter will override the automatically recognized value
noPom Do not generate pom.xml file false
customTemplates Additional custom code templates null
codeGeneratorHookClass Fully qualified class name of com.tencent.trpc.codegen.TRpcCodeGeneratorHook. Used in combination with customTemplates to achieve customized code generation. See the javadoc of the relevant class and this example for specific usage null