Graphical ASP.NET Core Introducing gRPC Service Template

Time:2019-9-1

It has long been heard that the service template of gRPC has been introduced into ASP.NET Core 3.0. It just happens that the home computer has just made a new system and then installed VS2019 to experience it. At the same time, record the process of experience. If you want to follow the steps in this article, you have to install the. NET Core 3.0 preview SDK first. As for the development tools I use VS2019, of course, you can also use VS Code.

A Brief Introduction to gRPC

GRPC is a language-independent high-performance remote procedure call (RPC) framework. For more information on the basics of gRPC, see the gRPC documentation page.

The main advantages of gRPC are:

  • Modern high performance lightweight RPC framework.
  • Protocol-first API development, default use of protocol buffer, allowing language-independent implementation.
  • Tools that can be used in multiple languages to generate strongly typed servers and clients.
  • Support client, server and bidirectional streaming processing calls.
  • Use Protobuf binary serialization to reduce network usage.

These advantages make gRPC suitable for:

  • Efficiency is critical for lightweight micro services.
  • Polyglot systems need to be developed in many languages.
  • Point-to-point real-time services that need to process requests or responses streamwise.

Initial Experience of gRPC Service Template on ASP.NET Core 3.0

Creating gRPC services

1. Open VS2019 and select New > Project from the Visual Studio File menu. (Since I am a newly opened VS, create a new project as shown in the following figure)

2. As shown in the figure below, select Create ASP.NET Core Web Application and click Next

3. On this page, enter the project name, location and solution name as shown in the figure below, and then click the “Create” button in the lower right corner to create it.

4. Do you think that clicking “Create” in the above steps is the end? That’s right to create gRPC service template, so click on the creation above and pop up the window as shown in the following figure. Here, select gRPC service template as shown in the following figure, and then click on the creation in the lower right corner again. That’s the real project to create.

5. After successful creation, the project structure shown in the following figure will appear

6. At this point, we have created a template for gRPC services. Next, let’s test it and then take a good look at the structure of the template.

Testing gRPC services

Open firstHelloGrpc.ServerThis server’s working directory, and thenShift + Right mouse buttonPop up the right-click menu shown in the following figure, and open the PS window as shown in the figure

2. Inputdotnet runThe command runs this gRPC server project, as shown in the following figure, to show that the server starts up normally and starts to listen on the corresponding port.

3. In the same way, we start the client and the client sends a greeting message with its name “GreeterClient” to the server. The server responds by sending a message “Hello GreeterClient” and displays it at the command prompt. As shown in the following figure:

4. At this point, the service side and the client side created by gRPC service template have been tested successfully. Now let’s explore the service template.

GRPC Template Analysis

stayHelloGrpc.ServerThere are several files in the end project of the service

  • greet.proto:greet.protoFile DefinitionGreeterGRPC, and is used to generate gRPC server assets.
  • Services folder: containsGreeterImplementation of services.
  • AppSettings. json: Contains configuration data, such as protocols used by Kestrel. (You must be familiar with ASP.NET Core)
  • Program.cs: Includes entry points for gRPC services. (You must be familiar with ASP.NET Core)
  • Startup.cs:IWebHostBuilderStart profile, which contains code to configure application behavior. (You must be familiar with ASP.NET Core)

GRPC ClientHelloGrpc.ClientDocuments:

Program. CS contains entry points and logic for gRPC clients.

Now let’s open each file and see what’s in it.

Proto file

proto

GRPC uses a convention-first API development approach. By default, Protocol Buffer is used as the Interface Design Language (IDL). this.protoThe file contains:

  • Definition of GRPC service.
  • Messages sent between client and server.

For more information on Protobuf file grammar, see Official Document (Prototype).

As created in our templategreet.protoThe document reads as follows:


syntax = "proto3";

package Greet;

// The greeting service definition.
service Greeter {
 // Sends a greeting
 rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
 string name = 1;
}

// The response message containing the greetings.
message HelloReply {
 string message = 1;
}
  • DefinitionGreeterService.
  • thisGreeterService DefinitionSayHelloRequest.
  • SayHelloSend outHelloRequestMessage and receiveHelloResponseInformation:
  • So you may have to ask, this.protoHow is the file included in the project? In fact, if you open the. csproject file, you will see that by adding the file to the project<Protobuf>In ItemGroup, as follows:

<ItemGroup>
 <Protobuf Include="..\Protos\*.proto" GrpcServices="Server" />
 <Content Include="@(Protobuf)" LinkBase="" />
</ItemGroup>

C# Tool Support for. proto Files

Toolkit Grpc. Tools is used from.protoFile generation C # file. The generated assets (files) have the following characteristics:

  • Every time a project is built, it is generated as needed.
  • The generated files will not be added to the project or checked in to source code management.
  • The generated C# file is contained inOBJCatalog.

Both server and client projects need this package.Grpc.ToolsYou can use the package manager or add it in Visual Studio<PackageReference>To project documents:

XML replication


<PackageReference Include="Grpc.Tools" Version="1.19.0-pre1" PrivateAssets="All" />

Toolkits are not required at run time, so they should be usedPrivateAssets="All".

Specific gRPC services in the Services folder

We knowGrpc.ToolsThe toolkit will be based on.protoThe definition of the file translates and generates the corresponding C type file.

For server-side assets, an abstract service base type is generated. The base type is contained in.protoDefinition of all GRPC calls contained in the file. Then, you will create a specific service implementation derived from this base type and implement the logic of GRPC calls. For the one described abovegreet.protoExample, which generates inclusion virtualizationSayHelloMethod abstractionGreeterBaseType. Specific realizationGreeterServiceRewrite this method and implement the logic to process GRPC calls.
Just asHelloGrpc.ServerIn the projectServices\GreeterService.csCode in


public class GreeterService : Greeter.GreeterBase
{
 public override Task<HelloReply> 
 SayHello(HelloRequest request, ServerCallContext context)
 {
 return Task.FromResult(new HelloReply
 {
  Message = "Hello " + request.Name
 });
 }
}

For the client, a GRPC call in a specific client type is generated..protoFiles are converted to methods of specific types that can be invoked. bygreet.protoThe example described above, a concrete oneGreeterClientType generation. thisGreeterClientType inclusionSayHelloMethod, you can call this method to start the GRPC call to the server.


public class Program
{
 static async Task Main(string[] args)
 {
 // Include port of the gRPC server as an application argument
 var port = args.Length > 0 ? args[0] : "50051";

 var channel = new Channel("localhost:" + port, ChannelCredentials.Insecure);
 var client = new Greeter.GreeterClient(channel);

 var reply = await client.SayHelloAsync(
     new HelloRequest { Name = "GreeterClient" });
 Console.WriteLine("Greeting: " + reply.Message);

 await channel.ShutdownAsync();

 Console.WriteLine("Press any key to exit...");
 Console.ReadKey();
 }
}

By default, server and client assets are generated respectively..protoThe file is contained in<Protobuf>Project team. To ensure that server assets are generated only in server projects,GrpcServicesProperty set toServer.

XML replication


<ItemGroup>
 <Protobuf Include="..\Protos\*.proto" GrpcServices="Server" />
 <Content Include="@(Protobuf)" LinkBase="" />
</ItemGroup>

Similarly, the property is set toClientGenerate only in customer projects.

Startup

stayStartupWe find that it is different from the ordinary ASP. NET Core program, as shown in the following figure:ConfigureServicesGRPC services are introduced into services, and thenConfigureAdding routing

And here you need to introduce three nuget packages related to gRPC

  • Grpc.AspNetCore.Server
  • Google. Protobuf for Protobuf message API.
  • Grpc.Tools

Here’s what I need to say.

ASP.NET Core middleware and function-sharing routing pipelines allow applications to be configured to serve other request handlers. Other request handlers, such as MVC controllers, can work in parallel with the configured GRPC service routing.

Other points to be explained

Integration with ASP.NET Core Interface

GRPC services have full access to ASP. NET Core functions, such as dependency injection (Di) and logging functions. For example, service implementations can parse recorder services in DI containers through constructors:


public class GreeterService : Greeter.GreeterBase
{
 public GreeterService(ILogger<GreeterService> logger)
 {
 }
}

By default, GRPC services can parse other DI services (Singleton, Scoped, or Transient) with any lifetime.

Analyzing HttpContext in GRPC Method

GRPC application interface provides access to some HTTP/2 message data, such as method, host, header, and trailers. Access is throughServerCallContextThe parameters are passed to each GRPC method:


public class GreeterService : Greeter.GreeterBase
{
 public override Task<HelloReply> 
 SayHello(HelloRequest request, ServerCallContext context)
 {
 return Task.FromResult(new HelloReply
 {
  Message = "Hello " + request.Name
 });
 }
}

ServerCallContextNot available in all ASP. NET interfacesHttpContextFull access.GetHttpContextExtended methods provide full access to httpContext representing underlying HTTP/2 messages in ASP.NET API:


public class GreeterService : Greeter.GreeterBase
{
 public override Task<HelloReply> SayHello(HelloRequest request, 
 ServerCallContext context)
 {
 var httpContext = context.GetHttpContext();

 return Task.FromResult(new HelloReply
 {
  Message = "Using https: " + httpContext.Request.IsHttps
 });
 }
}

Request volume data rate limit

By default, the Kestrel server is set to the minimum request body data rate. For client streaming and duplex streaming requests, this rate may not be satisfied, and the connection may be timed out. When GRPC services include client stream and duplex stream calls, the minimum request body data rate limit must be disabled:


public class Program
{
 public static void Main(string[] args)
 {
 CreateHostBuilder(args).Build().Run();
 }

 public static IHostBuilder CreateHostBuilder(string[] args) =>
  Host.CreateDefaultBuilder(args)
 .ConfigureWebHostDefaults(webBuilder =>
 {
 webBuilder.UseStartup<Startup>();
 webBuilder.ConfigureKestrel((context, options) =>
 {
  options.Limits.MinRequestBodyDataRate = null;
 });
 });
}

Reference Articles

gRPC services with C#

Tutorial: Get started with gRPC in ASP.NET Core

gRPC services with ASP.NET Core

Migrating gRPC services from C-core to ASP.NET Core

summary

Today, I share a little more, the purpose is to make the record as detailed as possible, as easy as possible to understand the language to describe, so that you can use it. In asp. net core 3.0, the grpc service is supported as a first-class citizen, so it is necessary for us to understand. Maybe a lot of friends will have doubts. Why use gRPC as a remote procedure call protocol when I use the Web API? On this issue, I am going to open a separate article to explain, and finally thank you for your reading, code words are not easy, more recommendation support bar!

Recommended Today

Hadoop MapReduce Spark Configuration Item

Scope of application The configuration items covered in this article are mainly for Hadoop 2.x and Spark 2.x. MapReduce Official documents https://hadoop.apache.org/doc…Lower left corner: mapred-default.xml Examples of configuration items name value description mapreduce.job.reduce.slowstart.completedmaps 0.05 Resource requests for Reduce Task will not be made until the percentage of Map Task completed reaches that value. mapreduce.output.fileoutputformat.compress false […]