.net core grpc realizes communication

Now the systems are all service-oriented, and there are many ways to achieve service-oriented .net core. We use grpc to achieve client-server communication.

grpc is an open source, high-performance, general-purpose RPC (Remote Procedure Call) framework released by Google. It uses the HTTP/2 protocol and uses ProtoBuf as a serialization tool to provide cross-language and cross-platform support. The following uses .net core to demonstrate how to use the grpc framework to implement communication.

 

Software version

.net core:2.0

grpc:1.11.0

 

Project structure

The InstallGrpc .net framework class library is only for obtaining the protocol code generation tools protoc.exe, grpc_csharp_plugin.exe, and has no other functions. If you already have tools, you can use them.

Snai.GrpcClient client.net core 2.0 console program

Snai.GrpcService.Hosting server.net core 2.0 console program

Snai.GrpcService.Impl protocol method implements .net standard 2.0 class library

Snai.GrpcService.Protocol generates protocol methods. Net standard 2.0 class library

operation result

Server

client

The client calls the server summation method successfully.

 

Project realization

1. Server

New Snai.GrpcService solution

1. Write the agreement

 Create a new Snai.GrpcService.Protocol protocol class library project, right-click on dependencies to manage NuGet packages, browse to find Grpc.Core version 1.11.0, Google.Protobuf version 3.5.1 package download and install

 Create a new msg.proto file in the project root directory, open the msg.proto file, and write the protocol based on the proto3 language in it for automatic generation to each language. If you need to learn more about the proto3 language, you can open the website Proto3 language guide . msg.proto code is as follows

 The definition currently uses the proto3 language and the package name (namespace generated for C#):

syntax = "proto3";

package Snai.GrpcService.Protocol;

1 service is defined with 1 method:

service MsgService{
  rpc GetSum(GetMsgNumRequest) returns (GetMsgSumReply){}
}

 Method's Received and Returned Parameters

message GetMsgNumRequest {
  int32 Num1 = 1;
  int32 Num2 = 2;
}

message GetMsgSumReply {
  int32 Sum = 1;
}

 2. Generate C# code from the protocol

The protoc.exe and grpc_csharp_plugin.exe tools are required to generate the protocol code. When you install Grpc.Tools under the .net framework project, you will get protoc.exe and grpc_csharp_plugin.exe , but the .net core project reference installation will not download the tools to the project directory. , so we need to build a .net framework project , I built an InstallGrpc .net framework class library to reference the installation tools.

There is a small episode of getting the tools here. I refer to Grpc.Tools version 1.11.0 to get protoc.exe and grpc_csharp_plugin.exe and copy them to the Snai.GrpcService.Protocol directory. protoc.exe, use grpc_csharp_plugin.exe under Grpc.Tools , protoc.exe under Google.Protobuf.Tools according to the current system selection, copy to Snai.GrpcService.Protocol directory.

First use Grpc.Tools , if it cannot be generated, then use grpc_csharp_plugin.exe under Grpc.Tools, protoc.exe under Google.Protobuf.Tools

Then create a new file named ProtocGenerate.cmd in the project and enter the following commands in it:

protoc -I . --csharp_out . --grpc_out . --plugin=protoc-gen-grpc=grpc_csharp_plugin.exe msg.proto

Then double-click to run, and two files "Msg.cs" and "MsgGrpc.cs" are generated under the project, so that all the work in the protocol part is completed , and the final project structure is as follows:

 3. Write the implementation code

 Create a new Snai.GrpcService.Impl implementation class library project, download and install the Grpc.Core package in the dependencies, and the project references Snai.GrpcService.Protocol

 Create a new MsgServiceImpl.cs class file in the project root directory, inherit the MsgService.MsgServiceBase protocol class, and implement the service method. The code is as follows:

using Grpc.Core;
using Snai.GrpcService.Protocol;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Snai.GrpcService.Impl
{
    public class MsgServiceImpl: MsgService.MsgServiceBase
    {
        public MsgServiceImpl()
        {
        }

        public override async Task<GetMsgSumReply> GetSum(GetMsgNumRequest request, ServerCallContext context)
        {
            var result = new GetMsgSumReply();

            result.Sum = request.Num1 + request.Num2;

            return result;
        }
    }
}

 Create a new RpcConfig.cs class file in the project root directory, write information such as binding services to the server, server address and port, etc., and implement the startup method. The code is as follows:

using Grpc.Core;
using Snai.GrpcService.Protocol;
using System;
using System.Collections.Generic;
using System.Text;

namespace Snai.GrpcService.Impl
{
    public static class RpcConfig
    {
        private static Server _server;

        public static void Start()
        {
            _server = new Server
            {
                Services = { MsgService.BindService(new MsgServiceImpl()) },
                Ports = { new ServerPort("localhost", 40001, ServerCredentials.Insecure) }
            };
            _server.Start();

            Console.WriteLine("grpc ServerListening On Port 40001");
            Console.WriteLine("Any key to exit...");
            Console.ReadKey();

            _server?.ShutdownAsync().Wait();
        }
    }
}

 The final project structure is as follows:

4. Write the server startup program

 Create a new Snai.GrpcService.Hosting console program, and the project references Snai.GrpcService.Impl

 Open the Program.cs file, modify the Main method, and add the service startup. The code is as follows:

using Snai.GrpcService.Impl;
using System;

namespace Snai.GrpcService.Hosting
{
    class Program
    {
        static void Main(string[] args)
        {
            RpcConfig.Start();
        }
    }
}

 The final project structure is as follows:

At this point, all the code for the server has been written, and the client is written below.

2. Client

 Create a new Snai.GrpcClient console program, download and install the Grpc.Core package in the dependencies, and the project references Snai.GrpcService.Protocol

 Create a new MsgServiceClient.cs class file in the project root directory, write the address port and other information for communication with the server, and call the server method. The code is as follows:

using Grpc.Core;
using Snai.GrpcService.Protocol;
using System;
using System.Collections.Generic;
using System.Text;

namespace Snai.GrpcClient
{
    public static class MsgServiceClient
    {
        private static Channel _channel;
        private static MsgService.MsgServiceClient _client;

        static MsgServiceClient()
        {
            _channel = new Channel("127.0.0.1:40001", ChannelCredentials.Insecure);
            _client = new MsgService.MsgServiceClient(_channel);
        }

        public static GetMsgSumReply GetSum(int num1, int num2)
        {
            return _client.GetSum(new GetMsgNumRequest
            {
                Num1 = num1,
                Num2 = num2
            });
        }
    }
}

 Open the Program.cs file, modify the Main method, get the result returned by the server, and display the result. The code is as follows:

using Snai.GrpcService.Protocol;
using System;

namespace Snai.GrpcClient
{
    class Program
    {
        static void Main(string[] args)
        {
            GetMsgSumReply msgSum = MsgServiceClient.GetSum(10, 2);

            Console.WriteLine("grpc Client Call GetSum():" + msgSum.Sum);

            Console.WriteLine("任意键退出...");
            Console.ReadKey();
        }
    }
}

 The final project structure is as follows:

 

So far all the code has been written

3. Start

Right-click to generate the solution, after the generation is complete, start the server first, and then start the client

Command line to the server directory Snai.GrpcService.Hosting\bin\Debug\netcoreapp2.0\, start the server with the command dotnet Snai.GrpcService.Hosting.dll

Command line to the client directory Snai.GrpcClient\bin\Debug\netcoreapp2.0\, start the client with the command dotnet Snai.GrpcClient.dll

 

The client calls the server method successfully and implements grpc

They communicate with each other through Server and Channel in Grpc.Core

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325692806&siteId=291194637