Microservice to service communication grpc

Time:2020-10-26

Grpc for communication between microservices

introduce

Grpc is a language independent high performance remote procedure call (RPC) framework,Grpc is a high-performance open source software framework based on HTTP 2.0 transport layer protocol released by Google. It provides a method to configure and manage network devices supporting multiple programming languages. Because it is an open source framework, the two sides of communication can carry out secondary development, so the communication between client and server will focus more on the content of business level, reducing the attention on the underlying communication implemented by grpc framework.

The main advantages of grpc are:

  • Modern high performance lightweight RPC framework.
  • Protocol first API development, protocol buffer is used by default, and language independent implementation is allowed.
  • Tools available in multiple languages to generate strongly typed servers and clients.
  • Support client, server and bidirectional streaming call.
  • Use protobuf binary serialization to reduce network usage.

These advantages make grpc suitable for:

  • Efficiency critical lightweight microservices.

  • Polyglot systems need to be developed in multiple languages.

  • Point to point real-time services that need to process streaming requests or responses.

The above is from Microsoft document

Interaction process of grpc in microservices

 

  1. After the grpc function is enabled, the switch acts as the grpc client, and the acquisition server acts as the grpc server;
  2. The switch will construct the corresponding data format (GPB / JSON) according to the subscribed events, and write the proto file through protocol buffers. The switch establishes grpc channel with the server, and sends request messages to the server through grpc protocol;
  3. After receiving the request message, the server will interpret the proto file through protocol buffers to restore the data structure with the first defined format for business processing;
  4. After sorting out the data, the server needs to use protocol buffers to recompile the response data and send the response message to the switch through grpc protocol;

After the switch receives the reply message, it ends the grpc interaction.The above figure shows the specific process of grpc interaction process, which is one of the telemetry trigger methods, called dial out mode. In short, grpc is to establish a connection between the client and server after the grpc function is enabled, and push the subscription data configured on the device to the server. We can see that the whole process needs to use protocol buffers to define the structured data to be processed in the proto file.

The use of grpc in microservices

1. To use grpc, you need to first introduce the grpc package

  The method of introducing package is: select service — > open management library package manager — > select browse — > input Grpc.AspNetCore — > to download

Note: if communication is required between two services, both services need to introduce grpc packets

2. Add grpc file

  Add the PROTOS folder (store all grpc files) in the server, and add a protocol buffer file in the folder with the suffix of. Proto

Design the file syntax of grpc. For more information about grpc file syntax, refer to some domestic blogs, such as “protobuf language guide. Details of proto file syntax”.

Syntax used in my project:

 syntax = "proto3";
 
 option csharp_namespace = "BS.GrpcServices.WorkTask";
 
 package BS.GrpcServices.WorkTask;
 
 service WorkTaskGrpc{
     rpc SubmitWorkTask(SubmitRequest) returns (SubmitResponse);
 }  
 
 message SubmitRequest{
     string Id = 1;
     int32  Survey = 2;
     string OrderId = 3;
 }
 
 message SubmitResponse{
     bool Result = 1;
 }

Code details:

  • BS.GrpcServices.WorkTask : generated assembly, for external reference, introduction method: Using BS.GrpcServices.WorkTask ;

  • Worktaskgrpc: a class in an assembly, which is also a method set for storing communication between services. After the assembly is introduced, methods in the class can be called by inheriting the current class

  • Submitworktask: a method in a class and a method for communication between two services. The main logic of communication exists in the current method

  • Submitrequest: the request represents the incoming parameter by default, and the submit matches the method

  • Submitresponse: response represents the return value by default, and submit matches the method

3. Project file configuration

  Double click the client’s service project, open the project file (. Csproj suffix file), and enter the following code in the file:

  After input, save it;

  Double click the client’s service project, open the project file (. Csproj suffix file), and enter the following code in the file:

  After input, save it;

4、 Startup.cs file

  Client open Startup.cs File, enter the following code:

AppContext.SetSwitch (" System.Net.Http . SocketsHttpHandler.Http2UnencryptedSupport ", true); // allow unencrypted http / 2 protocol
services.AddGrpcClient(options =>
{
     options.Address = new Uri(Configuration.GetValue("ServiceUrls:WorkTaskAPI"));
});

Code note: the above code is the last key point to get through grpc communication. The client can access the grpc assembly of the server by communicating with grpc through the above methods( BS.GrpcServices.WorkTask )

Special note: in the first line of the above code, the note is to allow the use of unencrypted http / 2 protocolIt must not be ignoredWithout this line of code, communication cannot be completed because grpc completes communication through the current protocol

5. Method implementation

  The implementation method is inherited by referencing the grpc assembly WorkTaskGrpc.WorkTaskGrpcBase Class. The implementation method is as follows:

using BS.GrpcServices.WorkTask;
 using Grpc.Core;
 
 namespace BS.WorkTask.API.Services
 {
     public class WorkTaskService : WorkTaskGrpc.WorkTaskGrpcBase
     {
         public override async Task SubmitWorkTask(SubmitRequest request, ServerCallContext context)
         {
             。。。。。。
 
             if(result.Succeeded)
                 return new SubmitResponse() { Result = true };
             else
                 return new SubmitResponse() { Result = false };
         }
     }
 }

The call method creates a WorkTaskGrpc.WorkTaskGrpcClient Object to call the method in the class through the object. The calling method is as follows:

using BS.GrpcServices.WorkTask;
 
 namespace BS.ApiAggregator.Controllers
 {
     [Route("api/worktask")]
     [ApiController]
     public class WorkTaskController: ControllerBase
     {
         WorkTaskGrpc.WorkTaskGrpcClient _workTaskClient;
         public WorkTaskController(WorkTaskGrpc.WorkTaskGrpcClient workTaskClient)
         {
             _workTaskClient = workTaskClient;
         }
 
         [HttpPost("submit")]
         public async Task SubmitAsync(GrpcServices.WorkTask.SubmitRequest request)
         {
             try
             {
                 var clientResult = await _workTaskClient.SubmitWorkTaskAsync(request);
                 if (clientResult.Result)
                 {
                     。。。。。。
                     return Ok(OperateResult.Success);
                 }
             }
             catch (Exception ex)
             {
                 。。。。。
             }
         }
     }
 }

  Reminder:

  1. The code omitted in the middle is processing logic, independent of grpc
  2. The call method is written in the client,The implementation method is written in the service server, and the two places can not be confused
  3. The client represents the caller and the server represents the callee

Summary:

  The configuration of grpc is relatively complex. For some microservices with few services, it is not recommended to use it. Instead, it can communicate through the traditional httpclient. Compared with the pure text transmission, grpc transfers binary data, which makes the transmission data smaller in size, lower in load, and more compact and efficient. In the case of larger incoming parameters, grpc can be used It is not flexible enough

This article is from:https://blog.csdn.net/zhaobw831/article/details/101638695

        https://baijiahao.baidu.com/s?id=1633335936037018920&wfr=spider&for=pc