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

John LuoJames 牛頓By John Luo and James Newton-King

gRPC 是一種語言中立、高效能的遠端程序呼叫, (RPC) framework。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.

警告

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.

適用于 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;
}

服務、用戶端和訊息的 .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 Greeter * * proto*檔案中的服務產生的類型。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.ForAddressA 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