Write a Go GRPC service

Source: Internet
Author: User

Pre-conditions:

Get grpc-go Source code

$ go Get google.golang.org/grpc

Simple example of source location:

$ cd $GOPATH/src/google.golang.org/grpc/examples/helloworld

More complex examples of source location:

$ cd $GOPATH/src/google.golang.org/grpc/examples/route_guide

写一个gRPC的服务,一般分下面几步:

    • Define a service within a. proto file.
    • Generate the server and client code with the protocol buffer compiler.
    • Use Grpc's Go API to implement a simple client and server for your service.
Defining services

Defining a service in a. proto file

Simple example service definition in: Examples/helloworld/helloworld/helloworld.proto

Definition of route_guide in: Examples/route_guide/routeguide/route_guide.proto

To define a service, you have to specify service in your. Proto file:

Then define the RPC method in your service, specifying the requested and response types.

GRPC allows you to define 4 types of service methods, which are used in the Routeguide service:

Simple RPC

A simple RPC, the client sends a request with a parameter to the server and waits for a response to return, just as the usual function calls.

Server-side streaming RPC

A server-side streaming RPC, the client sends a request to the server, gets a stream to read the returned message sequence. The client reads the returned stream until there is no message inside it. As you can see from the example, you can specify a server-side flow method by inserting the Stream keyword before the response type.

Client-side streaming RPC

A client-side streaming RPC, the client writes a message sequence and sends it to the server, as well as using the stream. Once the client finishes writing the message, it waits for the server to finish reading back its response. Specify a stream method for a client by specifying the Stream keyword before the request type.

Bi-directional streaming RPC

A bidirectional streaming RPC is a message sequence that both parties use to send a read-write stream. Two streams operate independently, so the client and server can read and write in any order they like: for example, the server can wait to receive all client messages before writing the response, or can alternately read and write messages, or other combinations of read and write. The order of messages in each stream is reserved. You can set the type of the method by adding the Stream keyword before the request and response.

Message type

The above looks like a function parameter, the return is worth it, because it involves a cross-server call, these actually pass the message. Our. Proto file also contains all the requested protocol buffer message type definitions and the type of response used in the service method-for example, the following point message type:

Generate server and client code

We need to build the server and client code with the protocol buffer compiler by protocol buffer's compiler PROTOC and a special grpc Go plugin.

During the simple period, there is a bash script that can help us generate the appropriate code codegen.sh (https://github.com/grpc/grpc-go/blob/master/codegen.sh)

Running codegen.sh Route_guide.proto can be generated in the current directoryroute_guide.pb.go 文件。

在这个产生的文件中, 既有 routeGuideClient 客户端代码部分, 也有 routeGuideRouteChatServer 服务器段代码部分。

Creating a server

This part of the source code in: Grpc-go/examples/route_guide/server/server.go

There are two parts to routeguide service work:

    • Implement the generated service interface of our service definition: Do the actual "work" of our service.
    • Run a GRPC server, listen for requests from the client, and return the response of the service.

Implement Routeguide

In the source code, we can see the implementation of the interface Routeguideserver routeguideserver data structure. This interface is in theroute_guide.pb.go中自动产生的。

Simple RPC

Getfeature, it gets a point object from the client and then returns a Feature containing the Feature information from the database.


The method passes in the RPC context object, as well as the client's point parameter. It returns the feature response information and error information.

In the method we traverse all the server-side saved information, find the location information to match, and then return it with a nil error to the client.

Server-side streaming RPC

Listfeatures is a server-side streaming RPC, and we send multiple Feature back to the client.

Here the request parameter is a Rectangle, the client expects to return multiple Feature, this time we use a Request object and a special routeguide_listfeaturesserver to write our response, Instead of getting the entry and return values in the method parameter.
In this method, we populate as many Feature objects as possible to return and write them to routeguide_listfeaturesserver using the Send () method of steam.

Finally, we return a nil error telling the GRPC that the write of the response has been completed.

If any errors occur during the call, we return a non-nil error;

Client-side streaming RPC

The client flow method Recordroute, we can get a point stream from the client, including the point information we need.

This time the method uses a routeguide_recordrouteserver stream that the server can use to read and write messages at the same time-it can receive the client message with its own RECV () method and return its individual response with the Sendandclose () method.

In the method body, we use the Routeguide_recordrouteserver Recv () method to repeatedly read the client's request to a Request object (in this scenario, point) until there are no more messages.

The server needs to check the error returned by Read () after each call. If the return value is nil, the stream is still intact and can continue reading;

If the return value is IO. EOF, the message flow ends and the server can return its routesummary.

If it has other values, we return the error as it is, and the GRPC layer converts it to the RPC state.

Bi-directional streaming RPC

Two-way streaming RPC routechat ().

The syntax for reading and writing here is similar to the client-side flow method, except that the server uses the stream's Send () method instead of Sendandclose () because it needs to write multiple responses. While the client and server side always get messages in the order in which they are written, they can read and write in any order--the operation of the stream is completely independent.

Start the server

Once we have implemented all the methods, we also need to start a GRPC server so that the client can use the service.

In order to build and start the server, we need:

    • Using Lis, err: = Net. Listen ("TCP", FMT. Sprintf (":%d", *port)) specifies the listening port that we expect the client to request.
    • Use GRPC. NewServer () Creates an instance of the GRPC server.
    • Register our service implementation on the GRPC server.
    • Use the server Serve () method and our port information area to implement blocking waits until the process is killed or Stop () is called.

Create Client 建立跟服务器的连接

To invoke the service method, we first create a GRPC conn. We passed it to GRPC. Dial () Incoming server address and port number to do this, as follows:

You can use Dialoptions in Grpc. Dial authentication (e.g., TLS,GCE certification, JWT certification), if the service has such a requirement-but for the Routeguide service, we do not need to do so.

Once Grpc Conn is set up, we need a client to execute RPC. We do this by using the Newrouteguideclient method provided by the. Proto generated PB package.

Call server method Simple RPC

Calling simple RPC getfeature is almost as intuitive as calling a local method.

Server-side streaming RPC

We pass in a context and request to the method. However, what we get back is an RouteGuide_ListFeaturesClient instance, not a Reply object. The client can use RouteGuide_ListFeaturesClient the stream to read the server's response.

We use RouteGuide_ListFeaturesClient the Recv() method to repeatedly read the response of the server to a response to a protocol buffer object (in this scenario Feature ) until the message is read: Each time the call completes, the client checks the Recv() error returned from the return err . If returned as nil , the stream is still intact and can continue to be read io.EOF , or, if returned, the message flow has ended, otherwise it must be a pass err -through RPC error.

Client-side streaming RPC

Routeguide_recordrouteclient has a Send () method that we can use to send a request to the server. Once we have finished using the Send () method to write the client request to the stream, we need to call the Closeandrecv () method of the stream, let Grpc know we have completed the write and expect the return reply. We get the state of RPC from the Err returned by CLOSEANDRECV (). If the status is nil, then the first return value of CLOSEANDRECV () will be a legitimate server answer.


Bi-directional streaming RPC

We only pass a context object to the function and get a stream that can be used to read and write.

Run example

Server-side:

$ go run server/server.go

Client:

$ go run client/client.go

Resources:

Chinese GRPC basic Go http://doc.oschina.net/grpc?t=60133

English GRPC basic Go http://www.grpc.io/docs/tutorials/basic/go.html

Write a Go GRPC service

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.