How to use gRPC
About gRPC
gRPC is a modern open source high performance RPC framework that can run in any environment. It can efficiently connect services in and across data centers with pluggable support for load balancing, tracing, health checking and authentication. It is also applicable in last mile of distributed computing to connect devices, mobile applications and browsers to backend services.
Overview
In gRPC a client application can directly call methods on a server application on a different machine as if it was a local object, making it easier for you to create distributed applications and services. As in many RPC systems, gRPC is based around the idea of defining a service, specifying the methods that can be called remotely with their parameters and return types. On the server side, the server implements this interface and runs a gRPC server to handle client calls. On the client side, the client has a stub (referred to as just a client in some languages) that provides the same methods as the server.
gRPC clients and servers can run and talk to each other in a variety of environments - from servers inside Google to your own desktop - and can be written in any of gRPC’s supported languages. So, for example, you can easily create a gRPC server in Java with clients in Go, Python, or Ruby. In addition, the latest Google APIs will have gRPC versions of their interfaces, letting you easily build Google functionality into your applications.
Working with Protocol Buffers
By default gRPC uses protocol buffers, Google’s mature open source mechanism for serializing structured data (although it can be used with other data formats such as JSON). Here’s a quick intro to how it works. If you’re already familiar with protocol buffers, feel free to skip ahead to the next section.
The first step when working with protocol buffers is to define the structure for the data you want to serialize in a proto file: this is an ordinary text file with a .proto extension. Protocol buffer data is structured as messages, where each message is a small logical record of information containing a series of name-value pairs called fields. Here’s a simple example:
Then, once you’ve specified your data structures, you use the protocol buffer compiler protoc to generate data access classes in your preferred language(s) from your proto definition. These provide simple accessors for each field (like name() and set_name()) as well as methods to serialize/parse the whole structure to/from raw bytes – so, for instance, if your chosen language is C++, running the compiler on the above example will generate a class called Person. You can then use this class in your application to populate, serialize, and retrieve Person protocol buffer messages.
As you’ll see in more detail in our examples, you define gRPC services in ordinary proto files, with RPC method parameters and return types specified as protocol buffer messages:
As you’ll see in more detail in our examples, you define gRPC services in ordinary proto files, with RPC method parameters and return types specified as protocol buffer messages:
gRPC also uses protoc with a special gRPC plugin to generate code from your proto file. However, with the gRPC plugin, you get generated gRPC client and server code, as well as the regular protocol buffer code for populating, serializing, and retrieving your message types. We’ll look at this example in more detail below.
This tutorial provides a basic Go programmer's introduction to working with gRPC.
By walking through this example you’ll learn how to:
Define a service in a .proto file.
Generate server and client code using the protocol buffer compiler.
Use the Go gRPC API to write a simple client and server for your service.
Then change your current directory to grpc-go/examples/route_guide:
A simple RPC where the client sends a request to the server using the stub and waits for a response to come back, just like a normal function call.
A server-side streaming RPC where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. As you can see in our example, you specify a server-side streaming method by placing the stream keyword before the response type.
A client-side streaming RPC where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a client-side streaming method by placing the stream keyword before the request type.
A bidirectional streaming RPC where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. You specify this type of method by placing the stream keyword before both the request and the response.
Our .proto file also contains protocol buffer message type definitions for all the request and response types used in our service methods - for example, here’s the Point message type:
As you can see, we call the method on the stub we got earlier. In our method parameters we create and populate a request protocol buffer object (in our case Point). We also pass a context.Context object which lets us change our RPC’s behaviour if necessary, such as time-out/cancel an RPC in flight. If the call doesn’t return an error, then we can read the response information from the server from the first return value.
Generate server and client code using the protocol buffer compiler.
Use the Go gRPC API to write a simple client and server for your service.
Example code and setup
The example code for our tutorial is in grpc/grpc-go/examples/route_guide. To download the example, clone the grpc-go repository by running the following command:
Then change your current directory to grpc-go/examples/route_guide:
Defining the service
Our first step (as you’ll know from the Overview) is to define the gRPC service and the method request and response types using protocol buffers. You can see the complete .proto file in examples/route_guide/routeguide/route_guide.proto
To define a service, you specify a named service in your .proto file:
To define a service, you specify a named service in your .proto file:
A simple RPC where the client sends a request to the server using the stub and waits for a response to come back, just like a normal function call.
A server-side streaming RPC where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. As you can see in our example, you specify a server-side streaming method by placing the stream keyword before the response type.
A client-side streaming RPC where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a client-side streaming method by placing the stream keyword before the request type.
A bidirectional streaming RPC where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. You specify this type of method by placing the stream keyword before both the request and the response.
Our .proto file also contains protocol buffer message type definitions for all the request and response types used in our service methods - for example, here’s the Point message type:
Generating client and server code
Next we need to generate the gRPC client and server interfaces from our .proto service definition. We do this using the protocol buffer compiler protoc with a special gRPC Go plugin. This is similar to what we did in the quickstart guide
From the route_guide example directory run :
Running this command generates the following file in the routeguide directory under the route_guide example directory:
route_guide.pb.go
This contains:
This contains:
All the protocol buffer code to populate, serialize, and retrieve our request and response message types
An interface type (or stub) for clients to call with the methods defined in the RouteGuide service.
An interface type for servers to implement, also with the methods defined in the RouteGuide service.
An interface type (or stub) for clients to call with the methods defined in the RouteGuide service.
An interface type for servers to implement, also with the methods defined in the RouteGuide service.
Creating the server
First let’s look at how we create a RouteGuide server. If you’re only interested in creating gRPC clients, you can skip this section and go straight to Creating the client (though you might find it interesting anyway!).
There are two parts to making our RouteGuide service do its job:
Implementing the service interface generated from our service definition: doing the actual “work” of our service.
Running a gRPC server to listen for requests from clients and dispatch them to the right service implementation.
You can find our example RouteGuide server in grpc-go/examples/route_guide/server/server.go. Let’s take a closer look at how it works.
Running a gRPC server to listen for requests from clients and dispatch them to the right service implementation.
You can find our example RouteGuide server in grpc-go/examples/route_guide/server/server.go. Let’s take a closer look at how it works.
Implementing RouteGuide
As you can see, our server has a routeGuideServer struct type that implements the generated RouteGuideServer interface:
As you can see, our server has a routeGuideServer struct type that implements the generated RouteGuideServer interface:
Simple RPC
routeGuideServer implements all our service methods. Let’s look at the simplest type first, GetFeature, which just gets a Point from the client and returns the corresponding feature information from its database in a Feature.
The method is passed a context object for the RPC and the client’s Point protocol buffer request. It returns a Feature protocol buffer object with the response information and an error. In the method we populate the Feature with the appropriate information, and then return it along with an nil error to tell gRPC that we’ve finished dealing with the RPC and that the Feature can be returned to the client.
Server-side streaming RPC
Now let’s look at one of our streaming RPCs. ListFeatures is a server-side streaming RPC, so we need to send back multiple Features to our client.
Now let’s look at one of our streaming RPCs. ListFeatures is a server-side streaming RPC, so we need to send back multiple Features to our client.
As you can see, instead of getting simple request and response objects in our method parameters, this time we get a request object (the Rectangle in which our client wants to find Features) and a special RouteGuide_ListFeaturesServer object to write our responses.
In the method, we populate as many Feature objects as we need to return, writing them to the RouteGuide_ListFeaturesServer using its Send() method. Finally, as in our simple RPC, we return a nil error to tell gRPC that we’ve finished writing responses. Should any error happen in this call, we return a non-nil error; the gRPC layer will translate it into an appropriate RPC status to be sent on the wire.
Client-side streaming RPC
Now let’s look at something a little more complicated: the client-side streaming method RecordRoute, where we get a stream of Points from the client and return a single RouteSummary with information about their trip. As you can see, this time the method doesn’t have a request parameter at all. Instead, it gets a RouteGuide_RecordRouteServer stream, which the server can use to both read and write messages - it can receive client messages using its Recv() method and return its single response using its SendAndClose() method.
Now let’s look at something a little more complicated: the client-side streaming method RecordRoute, where we get a stream of Points from the client and return a single RouteSummary with information about their trip. As you can see, this time the method doesn’t have a request parameter at all. Instead, it gets a RouteGuide_RecordRouteServer stream, which the server can use to both read and write messages - it can receive client messages using its Recv() method and return its single response using its SendAndClose() method.
In the method body we use the RouteGuide_RecordRouteServer’s Recv() method to repeatedly read in our client’s requests to a request object (in this case a Point) until there are no more messages: the server needs to check the error returned from Read() after each call. If this is nil, the stream is still good and it can continue reading; if it’s io.EOF the message stream has ended and the server can return its RouteSummary. If it has any other value, we return the error “as is” so that it’ll be translated to an RPC status by the gRPC layer.
Bidirectional streaming RPC
Finally, let’s look at our bidirectional streaming RPC RouteChat().
This time we get a RouteGuide_RouteChatServer stream that, as in our client-side streaming example, can be used to read and write messages. However, this time we return values via our method’s stream while the client is still writing messages to their message stream.
The syntax for reading and writing here is very similar to our client-streaming method, except the server uses the stream’s Send() method rather than SendAndClose() because it’s writing multiple responses. Although each side will always get the other’s messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently.
Starting the server
Once we’ve implemented all our methods, we also need to start up a gRPC server so that clients can actually use our service. The following snippet shows how we do this for our RouteGuide service:
Once we’ve implemented all our methods, we also need to start up a gRPC server so that clients can actually use our service. The following snippet shows how we do this for our RouteGuide service:
To build and start a server, we:
Specify the port we want to use to listen for client requests using lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port)).
Create an instance of the gRPC server using grpc.NewServer().
Register our service implementation with the gRPC server.
Call Serve() on the server with our port details to do a blocking wait until the process is killed or Stop() is called.
Create an instance of the gRPC server using grpc.NewServer().
Register our service implementation with the gRPC server.
Call Serve() on the server with our port details to do a blocking wait until the process is killed or Stop() is called.
Creating the client
In this section, we’ll look at creating a Go client for our RouteGuide service. You can see our complete example client code in grpc-go/examples/route_guide/client/client.go.
Creating a stub
To call service methods, we first need to create a gRPC channel to communicate with the server. We create this by passing the server address and port number to grpc.Dial() as follows:
To call service methods, we first need to create a gRPC channel to communicate with the server. We create this by passing the server address and port number to grpc.Dial() as follows:
You can use DialOptions to set the auth credentials (e.g., TLS, GCE credentials, JWT credentials) in grpc.Dial if the service you request requires that - however, we don’t need to do this for our RouteGuide service.
Once the gRPC channel is setup, we need a client stub to perform RPCs. We get this using the NewRouteGuideClient method provided in the pb package we generated from our .proto.
Once the gRPC channel is setup, we need a client stub to perform RPCs. We get this using the NewRouteGuideClient method provided in the pb package we generated from our .proto.
Calling service methods
Now let’s look at how we call our service methods. Note that in gRPC-Go, RPCs operate in a blocking/synchronous mode, which means that the RPC call waits for the server to respond, and will either return a response or an error.
Simple RPC
Calling the simple RPC GetFeature is nearly as straightforward as calling a local method.
Calling the simple RPC GetFeature is nearly as straightforward as calling a local method.
As you can see, we call the method on the stub we got earlier. In our method parameters we create and populate a request protocol buffer object (in our case Point). We also pass a context.Context object which lets us change our RPC’s behaviour if necessary, such as time-out/cancel an RPC in flight. If the call doesn’t return an error, then we can read the response information from the server from the first return value.
Server-side streaming RPC
Here’s where we call the server-side streaming method ListFeatures, which returns a stream of geographical Features. If you’ve already read Creating the server some of this may look very familiar - streaming RPCs are implemented in a similar way on both sides.
Here’s where we call the server-side streaming method ListFeatures, which returns a stream of geographical Features. If you’ve already read Creating the server some of this may look very familiar - streaming RPCs are implemented in a similar way on both sides.
As in the simple RPC, we pass the method a context and a request. However, instead of getting a response object back, we get back an instance of RouteGuide_ListFeaturesClient. The client can use the RouteGuide_ListFeaturesClient stream to read the server’s responses.
We use the RouteGuide_ListFeaturesClient’s Recv() method to repeatedly read in the server’s responses to a response protocol buffer object (in this case a Feature) until there are no more messages: the client needs to check the error err returned from Recv() after each call. If nil, the stream is still good and it can continue reading; if it’s io.EOF then the message stream has ended; otherwise there must be an RPC error, which is passed over through err.
Client-side streaming RPC
The client-side streaming method RecordRoute is similar to the server-side method, except that we only pass the method a context and get a RouteGuide_RecordRouteClient stream back, which we can use to both write and read messages.
The client-side streaming method RecordRoute is similar to the server-side method, except that we only pass the method a context and get a RouteGuide_RecordRouteClient stream back, which we can use to both write and read messages.
The RouteGuide_RecordRouteClient has a Send() method that we can use to send requests to the server. Once we’ve finished writing our client’s requests to the stream using Send(), we need to call CloseAndRecv() on the stream to let gRPC know that we’ve finished writing and are expecting to receive a response. We get our RPC status from the err returned from CloseAndRecv(). If the status is nil, then the first return value from CloseAndRecv() will be a valid server response.
Bidirectional streaming RPC
Finally, let’s look at our bidirectional streaming RPC RouteChat(). As in the case of RecordRoute, we only pass the method a context object and get back a stream that we can use to both write and read messages. However, this time we return values via our method’s stream while the server is still writing messages to their message stream.
Finally, let’s look at our bidirectional streaming RPC RouteChat(). As in the case of RecordRoute, we only pass the method a context object and get back a stream that we can use to both write and read messages. However, this time we return values via our method’s stream while the server is still writing messages to their message stream.
The syntax for reading and writing here is very similar to our client-side streaming method, except we use the stream’s CloseSend() method once we’ve finished our call. Although each side will always get the other’s messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently.
Try it out!
To compile and run the server, assuming you are in the folder $GOPATH/src/google.golang.org/grpc/examples/route_guide, simply:
留言
張貼留言