gRPC introduction and installation
1, What is gRPC
gRPC introduction
gRPC is a high-performance remote procedure call (RPC) framework open source by Google, which can run in any environment. The framework provides load balancing, tracking, intelligent monitoring, authentication and other functions, which can realize the efficient connection between systems.
gRPC official website
gRPC official website: https://grpc.io/.
gRPC source code
The official source code inventory of gRPC is placed on the github website and can be accessed publicly. The link to the home page of gRPC source code library is as follows: https://github.com/grpc/grpc
gRPC open source library supports many languages, such as C + +, c#, Dart, Go, Java, Node, Objective-C, PHP, Python, Ruby, WebJS, etc. developers can choose to view the implementation of the corresponding language in the github home library of gRPC.
gRPC call execution procedure
Because gRPC supports the implementation of multiple languages, gRPC supports the deployment, operation and mutual call of clients and servers in multiple language environments. Multi language environment interaction is shown in the following figure:
The default data format used in gRPC is protocol buffers.
2, Introduction to grpc go
What is grpc go
gRPC go library is the Golang language implementation version of gRPC library. You can access the source code of gRPC go library through GitHub homepage and download it. GitHub address of gRPC go homepage is as follows: https://github.com/grpc/grpc-go
Grpc go installation
go get command installation
When the network environment is unobstructed, you can use the go get command to install the grpc go Library:
go get -u google.golang.org/grpc
It should be noted that when using the above commands to install grpc go library, many developers often encounter problems in the network environment, resulting in download failure and hyperlink error. Common mistakes are:
package google.golang.org/grpc: unrecognized import path "google.golang.org/grpc" (https fetch: Get https://google.golang.org/grpc?go-get=1: dial tcp 216.239.37.1:443: i/o timeout)
If you encounter the timeout error of the linked server similar to the timeout above, it indicates that it is a network environment problem. At this time, you can install it through the second scheme.
Download installation
You can use the git clone command in the git tool to download the code from the github to the local. Clone command:
git clone https://github.com/grpc/grpc-go.git $GOPATH/src/google.golang.org/grpc
The second half of the above command is $gopath / SRC / Google golang. Org / grpc specifies to download the grpc go code base to a specific directory.
Dependency configuration
If clone is used in 2.2.2 to download and install, because the grpc-go library calls other external library contents, therefore, additional code base environment needs to be prepared. The libraries to be prepared are mainly golang Org package. golang. The Libraries under the. Org package can also be downloaded from github and put into the corresponding golang.org Org directory.
3, Define services
Write protobuf file
What we want to achieve is to make remote service calls through the gRPC framework. The first step should be to have services. Based on the previous knowledge, the gRPC framework supports the definition and generation of services.
By default, the gRPC framework uses protocol buffers as the interface definition language to describe the structure of network transmission messages. In addition, you can use protobuf to define service interfaces.
syntax = "proto3"; package message; option go_package="./;message"; //Order request parameters message OrderRequest { string orderId = 1; int64 timeStamp = 2; } //Order information message OrderInfo { string OrderId = 1; string OrderName = 2; string OrderStatus = 3; } //Order service definition service OrderService{ rpc GetOrderInfo(OrderRequest) returns (OrderInfo); }
While defining the data structure through the proto file, we also define the service interface to be implemented. GetOrderInfo is the definition of the specific service interface. In the GetOrderInfo interface definition, OrderRequest represents the parameter passed by the request, and OrderInfo represents the data parameter returned from the processing result.
4, Compile proto file
Environmental preparation
The defined proto files need to be compiled to generate go language code files for client programs and server programs. You can install plug-ins about proto in the go language environment.
go get -a github.com/golang/protobuf/protoc-gen-go
-a. after downloading the parameter, go install directly
gRPC compilation support
If defined The proto file, as shown in this case, contains the definition of the service interface, and we want to use the gRPC framework to implement RPC calls. Developers can use the plug-in compilation function provided by the protocol Gen go library to generate golang language code compatible with gRPC framework. You only need to specify the parameters of the plug-in based on the basic compilation command and tell the protocol compiler. The specific commands for compiling and generating service code compatible with gRPC framework are as follows:
protoc --go_out=plugins=grpc:. *.proto
gRPC implements RPC programming
Service interface implementation
Yes After proto defines the service interface and generates the corresponding go language file, it is necessary to implement the service interface. Define the service interface, which is implemented by OrderServiceImpl, and implement the details of GetOrderInfo. The service implementation logic is the same as that described above. The difference is the change of service interface parameters. The detailed code is as follows:
type OrderServiceImpl struct { } //Specific method implementation func (os *OrderServiceImpl) GetOrderInfo(ctx context.Context, request *message.OrderRequest) (*message.OrderInfo, error) { orderMap := map[string]message.OrderInfo{ "201907300001": message.OrderInfo{OrderId: "201907300001", OrderName: "clothes", OrderStatus: "Paid"}, "201907310001": message.OrderInfo{OrderId: "201907310001", OrderName: "snacks", OrderStatus: "Paid"}, "201907310002": message.OrderInfo{OrderId: "201907310002", OrderName: "food", OrderStatus: "Unpaid"}, } var response *message.OrderInfo current := time.Now().Unix() if (request.TimeStamp > current) { *response = message.OrderInfo{OrderId: "0", OrderName: "", OrderStatus: "Abnormal order information"} } else { result := orderMap[request.OrderId] if result.OrderId != "" { fmt.Println(result) return &result, nil } else { return nil, errors.New("server error") } } return response, nil }
gRPC implementation server
Using the gRPC framework, first implement the server program. Since gRPC framework is used for implementation, gRPC needs to be called for service method registration and listening processing. Service registration and listening processing are implemented as follows:
func main() { // Create an empty server object server := grpc.NewServer() // Register the OrderServiceImpl object with the server message.RegisterOrderServiceServer(server, new(OrderServiceImpl)) lis, err := net.Listen("tcp", ":8090") if err != nil { panic(err.Error()) } // Provide RPC service server.Serve(lis) }
gRPC implementation client
After realizing the server, implement the client program. Corresponding to the server program, call the method of gRPC framework to obtain the corresponding client program and realize the call of service. The specific programming implementation is as follows:
func main() { //1. Dail connection conn, err := grpc.Dial("localhost:8090", grpc.WithInsecure()) if err != nil { panic(err.Error()) } defer conn.Close() orderServiceClient := message.NewOrderServiceClient(conn) // Create a request object orderRequest := &message.OrderRequest{OrderId: "201907300001", TimeStamp: time.Now().Unix()} // Call RPC service using orderServiceClient orderInfo, err := orderServiceClient.GetOrderInfo(context.Background(), orderRequest) if orderInfo != nil { fmt.Println(orderInfo.GetOrderId()) fmt.Println(orderInfo.GetOrderName()) fmt.Println(orderInfo.GetOrderStatus()) } }