.Net Core3.0 use gRPC

What is gRPC

gRPC modern open source high performance RPC framework that can run in any environment. It can be effectively connected via pluggable support within the data center and across data center services, load balancing, tracking, health checks and identity verification. It also applies to the last mile of distributed computing, to the device, a mobile browser application and connected to the back-end service.

proto file

GRPC used to define the services and messages agreements; server and client share proto file.

Creating gRPC server using the new template

.NETcore 3.0 Creating a project provides a new gRPC template, you can easily use the ASP.NET  Core build gRPC service. Step by step we follow the steps to create AA.GrpcService service, of course, you can use the command: DOTNET new new GRPC -o GrpcGreeter

 Select gRPC Services templates

The final generation projects

greet.proto file

syntax = "proto3";

option csharp_namespace = "AA.GrpcService";

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;
}

GreeterService.cs

public class GreeterService : Greeter.GreeterBase
    {
        private readonly ILogger<GreeterService> _logger;
        public GreeterService(ILogger<GreeterService> logger)
        {
            _logger = logger;
        }

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

Startup.cs

  public void ConfigureServices(IServiceCollection services)
        {
            services.AddGrpc();
        }

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGrpcService<GreeterService>();

                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
                });
            });
        }

Once created, the package automatically includes a reference to create a proto file, services generate services, project templates to perform some operations, such as in the background

  • Create a dependency of all gRPC ASP.NET  Core project.
  • Create a service definition file named gRPC greet.proto.
  • Automatically generate all gRPC stub according to the service definition file.
  • GreeterService.cs stub create gRPC services based on automatically generated gRPC.
  • GRPC conduit arranged in Startup.cs mapped to the GreeterService.cs

Run Service

Creating gRPC client

Next, we create a console application as a client calls gRPC services;

Reference gRPC service: Right-add items = "Service Reference pop-up following pages;

Click OK

We look at the structure of the project, they will automatically help us deal with what operations:

  • Add a reference package:
  1.  package Grpc.Net.ClientFactory
  2.  package Google.Protobuf
  3.  package Grpc.Tools
  • Protos file (containing greet.proto) is automatically copied from AA.GrpcService project
  • Automatically add nodes
  <ItemGroup>
    <Protobuf Include="..\AA.GrpcService\Protos\greet.proto" GrpcServices="Client">
      <Link>Protos\greet.proto</Link>
    </Protobuf>
  </ItemGroup>

Finally, add the following code gRPC request;

 class Program
    {
        static async Task Main(string[] args)
        {
            using var channel = GrpcChannel.ForAddress("https://localhost:5005");
            var client = new Greeter.GreeterClient(channel);
            var response = await client.SayHelloAsync(new HelloRequest { Name = "gRPC" });
            Console.WriteLine("Greeting:" + response.Message);
            Console.WriteLine("Press a key to exit");
            Console.ReadKey();
        }
    }

Figure operating results:

Summary: .NETcore 3.0 makes use gRPC is very easy to integrate into the project, I hope this article so that you can understand .NETcore use in combination with gRPC. That applies to the following scenarios gRPC

  • Micro-services - gRPC designed for low latency and high throughput communication design. gRPC useful for efficient lightweight micro vital services.

  • Point real-time communication - gRPC has excellent support for bidirectional flow. gRPC services in real-time push messages without polling.

  • Multilingual environment - gRPC tool supports all popular development language, so gRPC is ideal for multi-language environments.

  • Network constrained environments - gRPC lightweight message using message format Protobuf was serialized. gRPC message is always less than the equivalent JSON message.

reference:

Guess you like

Origin www.cnblogs.com/chengtian/p/11714694.html