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

John 羅文James 的牛頓-王By 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.
  • 根據預設使用 Protocol Buffers 的合約優先式 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 systems where multiple languages are required for development.
  • 必須處理資料流要求或回應的點對點即時服務。Point-to-point real-time services that need to handle streaming requests or responses.

C#適用于 proto 檔案的工具支援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;
}

服務、用戶端和訊息的 .net 類型會透過在專案中包含 *proto檔案的方式自動產生:.NET types for services, clients and messages are automatically generated by including *.proto files in a project:

  • 將套件參考新增至Grpc套件。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.SayHello(
    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 服務.

Azure App Service 不支援 gRPCgRPC not supported on Azure App Service

警告

Azure App Service 或 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.

其他資源Additional resources