-
Notifications
You must be signed in to change notification settings - Fork 1
Usage
Assuming you have properly set up Piezo into your build, time has come to play with it. We'll work from an example — let's assume you want to implement a straightforward Web search engine. This is how you would define it in protobuf terms:
package example.search;
option "java_package" = "com.example.search";
message Result {
required string url = 1;
optional string title = 2;
repeated string snippets = 3;
}
message SearchResponse {
repeated Result result = 1;
}
message SearchRequest {
required string query = 1;
optional int32 page_number = 2;
optional int32 result_per_page = 3 [default = 10];
enum Corpus {
WEB = 1;
IMAGES = 2;
LOCAL = 3;
VIDEO = 4;
}
optional Corpus corpus = 4 [default = WEB];
}
service SearchService {
rpc Search(SearchRequest) returns (SearchResponse);
}
Stuff all that in a file under src/main/proto/example/search/search.proto
and run mvn compile
. You can now proceed to implement your search engine. For the sake of brevity, this example will always return the same one response to all requests.
public class MySearchEngine implements Search.SearchService {
public ListenableFuture<SearchResponse> search(SearchRequest request) {
Result result = Result.newBuilder().setUrl("http://www.42.com/")
.setTitle("The Meaning of Life…")
.build();
SearchResponse response = SearchResponse.newBuilder().addResult(result).build();
ListenableFuture<SearchResponse> future = future.create();
future.set(response);
return future;
}
}
Looks good! Now let's surface that implementation over, say, HTTP and JSON-RPC:
HttpJsonRpcServer server = new HttpJsonRpcServer(10000, "/rpc");
server.serviceGroup().addService(Search.SearchService.newService(new MySearchEngine()));
server.start();
And that's it! Your search engine is now a JSON-RPC API that the rest of the world can start using. From the client side, things are even simpler:
Client client = HttpJsonRpcClient.to(HostAndPort.fromParts("example.com", 10000), "/rpc");
SearchService.Interface searchEngine = SearchService.newStub(client);
From that point on, the remote service can be accessed through the searchEngine
variable:
searchEngine.search(SearchRequest.newBuilder().setQuery("My query").build()).get();