A backend serves gRPC and calls gRPC services, with all four RPC shapes: unary,
server streaming, client streaming and bidirectional streaming. Calls travel
over the server’s HTTP/2 listener, so a stock gRPC client in any language can
call a backend service. The same services also answer gRPC-Web over HTTP/1.1,
which is what the application’s @GrpcClient and browsers send.
Messages
A message is a @ProtoMessage class whose fields carry @ProtoField tags,
the same classes an application uses. The build writes a codec for each one,
<Message>ProtoCodec, with a shared INSTANCE. Nothing is read by reflection
at run time.
Serving a service
A @GrpcService bean serves one service. Each @Rpc method serves one RPC,
and its signature says which shape the RPC has:
@GrpcService("demo.Greeter")
public class Greeter {
@Rpc("SayHello") // unary
public HelloReply sayHello(HelloRequest request) {
return reply("Hello " + request.name);
}
@Rpc("Countdown") // server streaming
public void countdown(HelloRequest request, StreamObserver<HelloReply> out) {
for (int i = 3; i > 0; i--) {
out.onNext(reply(request.name + " " + i));
}
}
@Rpc("Collect") // client streaming
public HelloReply collect(Iterator<HelloRequest> requests) {
StringBuilder names = new StringBuilder();
while (requests.hasNext()) {
names.append(requests.next().name).append(' ');
}
return reply(names.toString().trim());
}
@Rpc("Chat") // bidirectional streaming
public void chat(Iterator<HelloRequest> in, StreamObserver<HelloReply> out) {
while (in.hasNext()) {
out.onNext(reply("Hi " + in.next().name));
}
}
}A method may also take a trailing
GrpcContext. It reads the request metadata and the deadline, says whether the client has gone, and adds response headers and trailers.Throwing
GrpcExceptionends the call with its status and message. Any other exception ends itUNKNOWN. The exception is logged, and its message isn’t sent to the client.A streaming method returns when its stream is done: the call ends
OKthen.An RPC that no bean serves is answered
UNIMPLEMENTED. A signature that isn’t one of the four shapes, and two methods serving the same RPC, are build errors.
The bean is an ordinary bean: it’s injected, takes @Transactional and the
other aspects, and is wired to the server by the build.
Generating from a .proto file
cn1:generate-grpc writes the messages from a .proto file. With
-Dcn1.grpc.target=backend, it writes each service for a backend:
mvn cn1:generate-grpc -Dcn1.grpc.proto=src/main/proto/greeter.proto \
-Dcn1.grpc.basePackage=com.example.greeter -Dcn1.grpc.target=backendGreeterService, an interface with one@Rpcmethod per RPC. A@GrpcService("demo.Greeter")class that implements it serves the service.GreeterClient, a class that calls the service through aGrpcChannel.
stream is accepted on either side of an RPC in this mode.
Calling a service
GrpcChannel calls a gRPC server: another backend, or any other
implementation. It’s immutable, so one channel can be shared:
GrpcChannel channel = GrpcChannel.forTarget("https://greeter.internal:8443")
.withMetadata("authorization", "Bearer " + token)
.withDeadlineMillis(2000);
HelloReply reply = channel.unary("/demo.Greeter/SayHello",
HelloRequestProtoCodec.INSTANCE, HelloReplyProtoCodec.INSTANCE, request);serverStreaminganswers aGrpcChannel.Call, anIteratorof the responses as they arrive.clientStreamingsends every message of anIteratorand answers the one response.bidiStreaminganswers an openCall:sendandcompletewrite the request stream, and the iterator reads responses meanwhile.A call that fails throws
GrpcException. A server that can’t be reached isUNAVAILABLE, and a call past its deadline isDEADLINE_EXCEEDED.
http:// targets are spoken as HTTP/2 without TLS (h2c), and https://
targets negotiate HTTP/2 through ALPN.
Protocol details
Messages may be compressed with gzip in either direction.
withGzip(true)compresses a channel’s requests.-binmetadata is base64 encoded on the wire and read as bytes byGrpcContext.getBinary.grpc-timeoutsets the call’s deadline. A handler that’s still running at the deadline isn’t interrupted: it should checkGrpcContext.isDeadlineExceededbetween units of work.Messages larger than 4 MiB are refused with
RESOURCE_EXHAUSTED, in either direction;GrpcServer.setMaxMessageSizeandGrpcChannel.withMaxMessageSizechange it.The calls of one HTTP/2 connection are served one at a time, in the order they arrive. Separate connections are served in parallel. Clients such as grpc-java put every call of a channel on one connection, so a long-lived streaming call (a watch or a subscription) holds back every call queued behind it. Give such calls a channel of their own.
Over gRPC-Web on HTTP/1.1, the response headers are sent before the handler runs, so headers a handler adds through
GrpcContextaren’t sent; trailers are.GrpcContext.isCancelledis answered only over HTTP/2; over gRPC-Web a departed client shows up as a failed write.A server-streaming call holds its connection until the stream is read to the end or the call is closed: a caller that stops early calls
close().
OpenTelemetry over gRPC
cn1.otel.protocol=grpc exports traces and metrics with OTLP over gRPC, to the
collector’s TraceService/Export and MetricsService/Export. The endpoint
defaults to http://localhost:4317, the collector’s gRPC port, and
cn1.otel.headers travel as call metadata. UNAVAILABLE,
RESOURCE_EXHAUSTED and DEADLINE_EXCEEDED are retried as the HTTP exporter
retries a 503; see Distributed tracing with OpenTelemetry.