1. Introduction

gRPC is an open source, cross-language, high-performance remote procedure call (RPC) framework from Google. gRPC enables client and server applications to communicate transparently and simplifies the construction of connected systems. It uses HTTP/2 as the communication protocol and Protocol Buffers as the serialization protocol.

Its main advantages:

  • Modern high performance lightweight RPC frame.
  • A prioritized API development that uses Protocol Buffers as the description language by default, allowing language-independent implementations.
  • Tools that can be used in multiple languages ​​to generate strongly typed servers and clients.
  • Support client, server bidirectional stream call.
  • Reduce network usage with Protocol Buffers binary serialization.
  • Transfer using HTTP/2

These advantages make gRPC very suitable:

  • High-Performance Lightweight Microservices – Designed for low latency and high throughput communications, gRPC is ideal for lightweight microservices that require high performance.
  • Multi-language hybrid development – gRPC tools support all popular development languages, making gRPC an ideal choice for multi-language development environments.
  • Point-to-point real-time communication – gRPC provides excellent support for bidirectional stream calls. The gRPC service can push messages in real time without polling.
  • Network Restricted Environment – Using Protocol Buffers to serialize messages, the serialization is always smaller than the equivalent JSON message, and the network bandwidth requirement is smaller than JSON.

The scenario of using gRPC is not recommended:

  • Browser accessible API – Browser does not fully support gRPC. Although gRPC-Web can provide browser support, it has limitations and introduces a server proxy.
  • Broadcast real-time communication – gRPC supports real-time communication via streaming, but there is no concept of broadcasting messages to registered connections
  • Interprocess communication – Processes must host HTTP/2 to accept incoming gRPC calls. For Windows, interprocess communication pipes are a faster method.

Excerpt from
Microsoft official documentation

The supported languages ​​are as follows:

using_gRPC_based_on_ASP.NET_Core_3.0_0.png

2. gRPC on .NET Core

gRPC is now very easy to use in .NET Core and ASP.NET Core, the open source address for implementation on .NET Core:
https://github.com/grpc/grpc-dotnet

, which is currently officially ASP. The NET project staff is maintained and has good access to the .NET Core ecosystem.

The gRPC features of .NET Core are as follows:


  • Grpc.AspNetCore

    A framework for hosting gRPC services on ASP.NET Core, integrating gRPC and ASP.NET Core functionality such as logging, dependency injection, authentication and authorization.

  • Grpc.Net.Client is

    based on HttpClient (HttpClient now supports HTTP/2) gRPC client

  • Grpc.Net.ClientFactory

    integrated with the gRPC client HttpClientFactoryallows centralized configuration of gRPC clients and injection into the application using DI

Create a gRPC service using ASP.NET Core

  1. The gRPC service can be quickly created with the templates provided by Visual Studio 2019 (16.3.0).

using_gRPC_based_on_ASP.NET_Core_3.0_1.png

Come and pull what the default source contains.

1 configuration file appsettings.json, more Kestrel enables HTTP/2 configuration, because gRPC is based on HTTP/2 communication

using_gRPC_based_on_ASP.NET_Core_3.0_2.png

② PB protocol file greet.protoused to automatically generate a service, the client and the message (represented by data transfer) in C # Class

using_gRPC_based_on_ASP.NET_Core_3.0_3.png

③ service class GreeterService, service class integrated Greeter.GreeterBasefrom proto automatically generates the file, the generated class obj\Debug\netcoreapp3.0catalog

using_gRPC_based_on_ASP.NET_Core_3.0_4.png

Automatically generated class:

using_gRPC_based_on_ASP.NET_Core_3.0_5.png

Startup.csClass 4 , adding the gRPC service to the endpoint route

using_gRPC_based_on_ASP.NET_Core_3.0_6.png

5 csproj project file containing proto file references

using_gRPC_based_on_ASP.NET_Core_3.0_7.png

2. Run

The first run will prompt you to trust the certificate, click “Yes”

using_gRPC_based_on_ASP.NET_Core_3.0_8.png

 

This is because HTTP/2 requires HTTPS. Although the HTTP/2 protocol does not explicitly require HTTPS, HTTPS is required for browser implementation in security, so HTTP/2 and HTTPS are basically a pair.

using_gRPC_based_on_ASP.NET_Core_3.0_10.png

Create a gRPC client

1. Add a .NET Core Console Application

2. Add packages via nuget: Grpc.Net.Client, Google.Protobuf, Grpc.Tools

using_gRPC_based_on_ASP.NET_Core_3.0_11.png

3. Copy the service’s proto file to the client

using_gRPC_based_on_ASP.NET_Core_3.0_12.png

4. Edit the client project file and add a description about the proto file.

<ItemGroup>
    <Protobuf Include="Protos\greet.proto" GrpcServices="Client" />
</ItemGroup>

Note that GrpcServices=”Client”this is the Client and the service is not the same

5. Generate client projects can generate classes through proto files

6. Add client call code

static async Task Main(string[] args)
{
    var channel = GrpcChannel.ForAddress("https://localhost:5001");
    var client = new Greeter.GreeterClient(channel);
    var reply = await client.SayHelloAsync(
        new HelloRequest { Name = "晓晨" });
    Console.WriteLine("Greeter 服务返回数据: " + reply.Message);
    Console.ReadKey();
}

7. Start the service first, then run the client

using_gRPC_based_on_ASP.NET_Core_3.0_13.png

Here you can see that the client successfully called the service and received the returned message.

5. Write a service by yourself

The Greeter service we used earlier was created automatically by the template, now let’s write a service ourselves.

Write a “cat service”

1. Define the proto file LuCat.protoand add a description to the csproj project file

syntax = "proto3";

option csharp_namespace = "AspNetCoregRpcService";

import "google/protobuf/empty.proto";
package LuCat; //

//defien service
service LuCat{
    //
    rpc SuckingCat(google.protobuf.Empty) returns(SuckingCatResult);
}

message SuckingCatResult{
    string message=1;
}


2. Realize the service LuCatService.cs

public class LuCatService:LuCat.LuCatBase
{
    private static readonly List<string> Cats=new List<string>(){"英短银渐层","英短金渐层","美短","蓝猫","狸花猫","橘猫"};
    private static readonly Random Rand=new Random(DateTime.Now.Millisecond);
    public override Task<SuckingCatResult> SuckingCat(Empty request, ServerCallContext context)
    {
        return Task.FromResult(new SuckingCatResult()
        {
            Message = $"您吸了一只{Cats[Rand.Next(0, Cats.Count)]}"
        });
    }
}

3. StartupRegistration endpoint route

endpoints.MapGrpcService<LuCatService>();

4. Add client calls

var catClient = new LuCat.LuCatClient(channel);
var catReply = await catClient.SuckingCatAsync(new Empty());
Console.WriteLine("调用撸猫服务:"+ catReply.Message);

5. Run the test

using_gRPC_based_on_ASP.NET_Core_3.0_15.png

Six. Practical skills

Tip 1

In the steps in the previous section, we need to copy proto between the service and the client, which is a step that can be omitted.

1. Copy the Protos folder to the solution root directory (the directory where the sln file is located)

using_gRPC_based_on_ASP.NET_Core_3.0_16.png

2. Delete the Protos folder in the client and service project

3. Add a description about the proto file in the client project file csproj

  <ItemGroup>
    <Protobuf Include="..\..\Protos\greet.proto" GrpcServices="Client" Link="Protos\greet.proto" />
  </ItemGroup>

4. Add a description about the proto file in the service project file csproj

  <ItemGroup>
    <Protobuf Include="..\..\Protos\greet.proto" GrpcServices="Server" Link="Protos\greet.proto" />
  </ItemGroup>

In the actual project, please calculate the relative path by yourself.

5. These two projects are all using a proto file, just use this file to maintain.

using_gRPC_based_on_ASP.NET_Core_3.0_17.png

Tip 2

We use it in actual projects, there must be multiple proto files, do we have to update the csproj file every time we add a proto file?

We can use the MSBuild variable to help us complete, we will introduce the proto file information in the csproj project file to modify.

Server:

  <ItemGroup>
    <Protobuf Include="..\..\Protos\*.proto" GrpcServices="Server" Link="Protos\%(RecursiveDir)%(Filename)%(Extension)" />
  </ItemGroup>

Client:

  <ItemGroup>
    <Protobuf Include="..\..\Protos\*.proto" GrpcServices="Client" Link="Protos\%(RecursiveDir)%(Filename)%(Extension)" />
  </ItemGroup>

Example:

using_gRPC_based_on_ASP.NET_Core_3.0_18.png

Summary

gRPC is currently a very mature high-performance RPC framework. The current ecology is very good. Many companies’ products or open source projects are using gRPC. With it, I believe it will make it easier for us to build .NET Core. Microservices allow .NET Core to better access the gRPC ecosystem. I have to say that this is one of the most exciting features of .NET Core 3.0.

Reference materials:

If you can’t access the proto3 documentation, here’s an
offline web version

(please save it as a download and open it with Chrome)

Orignal link:https://www.cnblogs.com/stulzq/p/11581967.html