Protobuf Service Descriptors

gRPC uses the Protobuf .proto file format to define your messages, services and some aspects of the code generation.

For an in-depth description see the Protocol buffers documentation, but here are a few quick examples:

Messages

Messages are defined in the same way protobuf definitions are used for serialization:

// The request message containing the user's name.
message HelloRequest {
    string name = 1;
}

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

Services

Those messages can be used to define services:

////////////////////////////////////// The greeting service definition.
service GreeterService {
    //////////////////////
    // Sends a greeting //
    ////////*****/////////
    //      HELLO       //
    ////////*****/////////
    rpc SayHello (HelloRequest) returns (HelloReply) {}

    // Comment spanning
    // on several lines
    rpc ItKeepsTalking (stream HelloRequest) returns (HelloReply) {}

    /*
     * C style comments
     */
    rpc ItKeepsReplying (HelloRequest) returns (stream HelloReply) {}

    /* C style comments
     * on several lines
     * with non-empty heading/trailing line */
    rpc StreamHellos (stream HelloRequest) returns (stream HelloReply) {}
}

Both the request and the response consist of either a single message or a stream of messages.

Code generation options

There are a number of options that can be set in the .proto definition that influence how the code is generated:

option java_multiple_files = true;
option java_package = "example.myapp.helloworld.grpc";
option java_outer_classname = "HelloWorldProto";

package helloworld;

The (optional) package in the .proto is used to resolve references from one .proto file to another. It can also be used for the package name in the generated code, but it is common to use the separate java_package option to override it. In the Akka gRPC examples the convention is to choose a java_package ending in .grpc to easily distinguish between generated and regular code.

The Java code generation places all message classes in a large class whose name is determined by the java_outer_classname setting. By setting the java_multiple_files option, the message classes will be generated in separate files, but the ‘outer’ class is still generated with some metadata and utilities.

The Scala code generation uses the mechanism described in the ScalaPB documentation with the flat_package option enabled.

Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.