Define a gRPC Service

Distributed Services with Go — by Travis Jeffery (32 / 84)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Goals When Building a Service | TOC | Compile with the gRPC Plugin 👉

A gRPC service is essentially a group of related RPC endpoints — exactly how they’re related is up to you. A common example is a RESTful grouping where the relation is that the endpoints operate on the same resource, but the grouping could be looser than that. In general, it’s just a group of endpoints needed to solve some problem. In our case, the goal is to enable people to write to and read from their log.

Creating a gRPC service involves defining it in protobuf and then compiling your protocol buffers into code comprising the client and server stubs that you then implement. To get started, open log.proto, the file where we defined our Record message, and add the following service definition above those messages:

ServeRequestsWithgRPC/api/v1/log.proto

​ ​service​ Log {
​ ​rpc​ Produce(ProduceRequest) ​returns​ (ProduceResponse) {}
​ ​rpc​ Consume(ConsumeRequest) ​returns​ (ConsumeResponse) {}
​ ​rpc​ ConsumeStream(ConsumeRequest) ​returns​ (stream ConsumeResponse) {}
​ ​rpc​ ProduceStream(stream ProduceRequest) ​returns​ (stream ProduceResponse) {}
​ }

The service keyword says that this is a service for the compiler to generate, and each RPC line is an endpoint in that service, specifying the type of request and response the endpoint accepts. The requests and…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.