In many cases we want to define messages and services in one place using one language. This example shows how to do it in a simple way.
Consider you have an input - proto file like this:
message SearchRequest {
required string keyword = 1;
}
message SearchResponse {
repeated string result = 1;
}
service SearchService {
rpc search (SearchRequest) returns (SearchResponse);
}
The goal is to generate java code for messages and service interfaces.
In this example we use protostuff-maven-plugin
.
There are three main components:
- search.proto - contains message and service definitions
- service.java.stg - template for code generation (service only)
- pom.xml - contains a configuration for
protostuff-maven-plugin
You should use same syntax as for protobuf compiler.
Example:
service SearchService {
rpc search (SearchRequest) returns (SearchResponse);
rpc extendedSearch (ExtendedSearchRequest) returns (SearchResponse);
}
For basic protostuff code generation examples please check this.
In our example we want to generate service interface that:
- Returns Guava's ListenableFuture<T> as a method return type, where
T
is a service response message. - Takes single argument
U
- the service request message.
Rule service_block
specifies how to render service interface/class.
In the example we are using two service properties and some method properties:
Service properties:
Property | Description |
---|---|
name | Service name |
rpcMethods | Collection of RpcMethod definitions of this service |
Service method properties:
Property | Description |
---|---|
name | Service method name |
returnType | Service method return type (message) |
argType | Service method argument type (message) |
This diagram shows all properties that are accessible in this block:
You can specify template for service code generation as an additional output for protostuff-maven-plugin:
<source>src/main/proto/search.proto</source>
<outputDir>target/generated-sources</outputDir>
<output>
java_bean,
src/main/st/service.java.stg
</output>
This way you can use
- any template for your messages
- custom template for services
As usually:
mvn clean install
After compilation you can go to target/generated-sources
and examine generated code.
Generated service interface:
package io.protostuff.example.search;
import com.google.common.util.concurrent.ListenableFuture;
public interface SearchService {
ListenableFuture<SearchResponse> search(SearchRequest request);
ListenableFuture<SearchResponse> extendedSearch(ExtendedSearchRequest request);
}