GRPC is a language-independent, high-performance remote procedure call (RPC) framework.
- GRPC. IO/docs/guides…
- Github.com/grpc/grpc-d…
- Docs.microsoft.com/zh-cn/aspne…
The main advantages of gRPC
- Modern high-performance lightweight RPC framework.
- Protocol-first API development, using protocol buffers by default, allows language-independent implementations.
- Tools available in multiple languages to generate strongly typed servers and clients.
- Supports client, server, and two-way streaming calls.
- Use Protobuf binary serialization to reduce network usage.
These advantages make gRPC suitable for use
- Lightweight microservices where efficiency is critical.
- Polyglot systems require multiple languages for development.
- Point-to-point real-time services that need to handle streaming processing requests or responses.
GRPC is now very simple to use in.NET Core and ASP.NET Core, and has been open source, it is currently maintained by Microsoft official ASP.NET project staff, good access to the.NET Core ecosystem.
Next, I’ll show you how to use gRPC. To use gRPC, you need.NET Core 3.1 or higher SDK support. GRPC is divided into server and client, so create two projects, one console as client gRPC_ClientDemo, and one ASP.NET Core as server gRPC_ServerDemo.
Add the grpc.aspnetcore component to the server
Install-Package Grpc.AspNetCore
Copy the code
Then add services.addgrpc () to startup. cs.
public void ConfigureServices(IServiceCollection services)
{
services.AddGrpc();
}
Copy the code
Because gRPC communicates over HTTP/2, you need to add the Kestrel HTTP/2 enabled configuration to the configuration file.
{
"Kestrel": {
"EndpointDefaults": {
"Protocols": "Http2"}}}Copy the code
GRPC is different from traditional API, we need to define our own PROto file, gRPC uses protocol first method for API development. By default, the protocol buffer (Protobuf) is used as the interface design language (IDL). *.proto files contain:
- Definition of gRPC service.
- A message sent between a client and a server.
For more information on the syntax of a Protobuf file, see the official documentation (Protobuf).
Proto files will definitely exist in the actual development of multiple, one trick is to put proto files in a folder, and then use the Link association of Protobuf, so that only one proTO file can be maintained.
Microsoft also helps us to provide dotnet-grPC,.net Core global tools, please run the following command:
dotnet tool install -g dotnet-grpc
Copy the code
Dotnet-grpc can be used to add a Protobuf reference as a
<Protobuf Include="Protos\greet.proto" GrpcServices="Server" />
Copy the code
For details, see the documentation: docs.microsoft.com/zh-cn/aspne…
Add the Proto folder to the solution access folder root, create a Hello. protoproto file, and connect it to both projects separately.
Now to write Hello. proto, add a SayHello method.
syntax = "proto3";
package hello; // Define the package name
// Define the service
service HelloService {
// Define a SayHello method
rpc SayHello (HelloRequest) returns (HelloReply);
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
Copy the code
Then implement the service by adding a greeterService.cs to the server.
using Grpc.Core;
using Hello;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
namespace gRPC_ServerDemo.Services
{
public class GreeterService : HelloService.HelloServiceBase
{
private readonly ILogger _logger;
public GreeterService(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<GreeterService>();
}
public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
{
_logger.LogInformation($"Sending hello to {request.Name}");
return Task.FromResult(new HelloReply { Message = "Hello "+ request.Name }); }}}Copy the code
HelloService. HelloServiceBase proto file is automatically generated class for us.
The overloaded SayHello() method is called, a log is recorded and the field name passed in by the client is returned.
Add the GreeterService service to the routing pipe in the configuration file
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/".async context =>
{
await context.Response.WriteAsync("Hello World!");
});
endpoints.MapGrpcService<GreeterService>();
});
Copy the code
Support our server to complete, start the server to get the boot address, https://localhost:5001.
Now go to the client configuration address to invoke the service we wrote. Before we can start, we need to reference the following nuget packages in the client solution.
Install-Package Grpc.Net.Client
Install-Package Google.Protobuf
Install-Package Grpc.Tools
Copy the code
using Grpc.Net.Client;
using Hello;
using System;
using System.Threading.Tasks;
namespace gRPC_ClientDemo
{
class Program
{
static async Task Main(string[] args)
{
using var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client = new HelloService.HelloServiceClient(channel);
await UnaryCallExample(client);
}
private static async Task UnaryCallExample(HelloService.HelloServiceClient client)
{
var reply = await client.SayHelloAsync(new HelloRequest { Name = "Star Plus" });
Console.WriteLine("Greeting: "+ reply.Message); }}}Copy the code
Start the server and client to see the effect, successfully send messages and get messages.