微服務之間通信的選擇之gRPC

介紹

gRPC是一種與語言無關的高性能遠程過程調用 (RPC) 框架。

gRPC 的主要優點是:

  • 現代高性能輕量級 RPC 框架。
  • 協定優先 API 開發,默認使用協議緩衝區,允許與語言無關的實現。
  • 可用於多種語言的工具,以生成強類型服務器和客戶端。
  • 支持客戶端、服務器和雙向流式處理調用。
  • 使用 Protobuf 二進制序列化減少對網絡的使用。

這些優點使 gRPC 適用於:

  • 效率至關重要的輕量級微服務。
  • 需要多種語言用於開發的 Polyglot 系統。
  • 需要處理流式處理請求或響應的點對點實時服務。

以上摘自Microsoft Document

.NET中gRPC的簡單使用

ASP.NET Core中 gRPC Server 配置:

public void ConfigureServices(IServiceCollection services)
{
    services.AddGrpc();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapGrpcService<GreeterService>();
    });
}

ASP.NET Core中 gRPC Server 服務類:

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

greet.proto

syntax = "proto3";

option csharp_namespace = "GrpcServer";

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

有關 protobuf 文件語法的詳細信息,參考官方文檔(protobuf)

客戶端:
添加對應的包,複製服務端的proto文件並配置:

  <ItemGroup>
    <PackageReference Include="Google.Protobuf" Version="3.9.2" />
    <PackageReference Include="Grpc.Net.Client" Version="2.23.2" />
    <PackageReference Include="Grpc.Tools" Version="2.24.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <Protobuf Include="Protos\greet.proto" GrpcServices="Client" />
  </ItemGroup>

直接生成客戶端項目即可根據proto生成對應的類文件。
然後通過如下代碼進行調用:

static async Task Main(string[] args)
{
    var channel = GrpcChannel.ForAddress("https://localhost:5001");
    var client = new Greeter.GreeterClient(channel);
    var reply = await client.SayHelloAsync(new HelloRequest { Name = "張三" });
    Console.WriteLine(reply.Message);
}

運行程序:
在這裏插入圖片描述

proto中標量值類型與C#對應關係

.proto Type C# Type Notes
double double
float float
int32 int Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint32 instead.
int64 long Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint64 instead.
uint32 uint Uses variable-length encoding.
uint64 ulong Uses variable-length encoding.
sint32 int Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s.
sint64 long Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int64s.
fixed32 uint Always four bytes. More efficient than uint32 if values are often greater than 2282^{28}.
fixed64 ulong Always eight bytes. More efficient than uint64 if values are often greater than 2562^{56} .
sfixed32 int Always four bytes.
sfixed64 long Always eight bytes.
bool bool
string string A string must always contain UTF-8 encoded or 7-bit ASCII text, and cannot be longer than 2322^{32}.
bytes ByteString May contain any arbitrary sequence of bytes no longer than 2322^{32}.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章