.NET Core 上的 gRPC 的简介Introduction to gRPC on .NET Core

作者:John LuoJames Newton-KingBy John Luo and James Newton-King

gRPC 是一种与语言无关的高性能远程过程调用 (RPC) 框架。gRPC is a language agnostic, high-performance Remote Procedure Call (RPC) framework.

gRPC 的主要优点是:The main benefits of gRPC are:

  • 现代高性能轻量级 RPC 框架。Modern, high-performance, lightweight RPC framework.
  • 协定优先 API 开发,默认使用协议缓冲区,允许与语言无关的实现。Contract-first API development, using Protocol Buffers by default, allowing for language agnostic implementations.
  • 可用于多种语言的工具,以生成强类型服务器和客户端。Tooling available for many languages to generate strongly-typed servers and clients.
  • 支持客户端、服务器和双向流式处理调用。Supports client, server, and bi-directional streaming calls.
  • 使用 Protobuf 二进制序列化减少对网络的使用。Reduced network usage with Protobuf binary serialization.

这些优点使 gRPC 适用于:These benefits make gRPC ideal for:

  • 效率至关重要的轻量级微服务。Lightweight microservices where efficiency is critical.
  • 需要多种语言用于开发的 Polyglot 系统。Polyglot systems where multiple languages are required for development.
  • 需要处理流式处理请求或响应的点对点实时服务。Point-to-point real-time services that need to handle streaming requests or responses.

警告

Azure 应用服务或 IIS 当前不支持 ASP.NET Core gRPCASP.NET Core gRPC is not currently supported on Azure App Service or IIS. Http.Sys 的 HTTP/2 实现不支持 gRPC 依赖的 HTTP 响应尾随标头。The HTTP/2 implementation of Http.Sys does not support HTTP response trailing headers which gRPC relies on. 有关详细信息,请参阅此 GitHub 问题For more information, see this GitHub issue.

.proto 文件的 C# 工具支持C# Tooling support for .proto files

gRPC 使用协定优先方法进行 API 开发。gRPC uses a contract-first approach to API development. 在 *.proto** 文件中定义服务和消息:Services and messages are defined in *.proto files:

syntax = "proto3";

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply);
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

通过在项目中包含 *.proto** 文件,可以自动生成用于服务、客户端和消息的 .NET 类型:.NET types for services, clients and messages are automatically generated by including *.proto files in a project:

  • 将包引用添加到 Grpc.Tools 包。Add a package reference to Grpc.Tools package.
  • 将 *.proto 文件添加到 <Protobuf> 项目组。Add *.proto files to the <Protobuf> item group.
<ItemGroup>
  <Protobuf Include="Protos\greet.proto" />
</ItemGroup>

有关 gRPC 工具支持的详细信息,请参阅 使用 C# 的 gRPC 服务For more information on gRPC tooling support, see 使用 C# 的 gRPC 服务.

ASP.NET Core 上的 gRPC 服务gRPC services on ASP.NET Core

gRPC 服务可以托管在 ASP.NET Core 上。gRPC services can be hosted on ASP.NET Core. 这些服务与常用的 ASP.NET Core 功能(例如日志记录、依赖关系注入(DI)、身份验证和授权)完全集成。Services have full integration with popular ASP.NET Core features such as logging, dependency injection (DI), authentication and authorization.

gRPC 服务项目模板提供了一个入门版服务:The gRPC service project template provides a starter service:

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)
    {
        _logger.LogInformation("Saying hello to {Name}", request.Name);
        return Task.FromResult(new HelloReply 
        {
            Message = "Hello " + request.Name
        });
    }
}

GreeterService 继承自 GreeterBase 类型,后者是从 *.proto** 文件的 Greeter 服务生成的。GreeterService inherits from the GreeterBase type, which is generated from the Greeter service in the *.proto file. Startup.cs** 中的客户端可以访问该服务:The service is made accessible to clients in Startup.cs:

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

若要了解有关 ASP.NET Core 上的 gRPC 服务的详细信息,请参阅 使用 ASP.NET Core 的 gRPC 服务To learn more about gRPC services on ASP.NET Core, see 使用 ASP.NET Core 的 gRPC 服务.

使用 .NET 客户端调用 gRPC 服务Call gRPC services with a .NET client

gRPC 客户端是从 *.proto 文件生成的具体客户端类型。gRPC clients are concrete client types that are generated from *.proto files. 具体 gRPC 客户端具有转换为 *.proto 文件中 gRPC 服务的方法。The concrete gRPC client has methods that translate to the gRPC service in the *.proto file.

var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client = new Greeter.GreeterClient(channel);

var response = await client.SayHelloAsync(
    new HelloRequest { Name = "World" });

Console.WriteLine(response.Message);

gRPC 客户端是使用通道创建的,该通道表示与 gRPC 服务的长期连接。A gRPC client is created using a channel, which represents a long-lived connection to a gRPC service. 可以使用 GrpcChannel.ForAddress 创建通道。A channel can be created using GrpcChannel.ForAddress.

有关创建客户端、调用不同服务方法的详细信息,请参阅 使用 .NET 客户端调用 gRPC 服务For more information on creating clients, and calling different service methods, see 使用 .NET 客户端调用 gRPC 服务.

其他资源Additional resources