C# 實現 gRPC 服務和呼叫

韩梦芫發表於2024-04-23

gRPC 是一種與語言無關的高效能遠端過程呼叫 (RPC) 框架。

主要優點如下:
1.高效能輕量化。
2.協議優先的 API 定義模式,預設使用協議緩衝區,允許與語言無關的實現。
3.可用於多種語言的工具,以生成強型別伺服器和客戶端。
4.支援客戶端、伺服器和雙向流式處理呼叫。
5.使用 Protobuf 二進位制序列化減少對網路的使用。

gRPC 服務可以託管在 ASP.NET Core 上。 這些服務與日誌記錄、依賴關係注入 (DI)、身份驗證和授權等 ASP.NET Core 功能完全整合。

本文示例包含服務端實現和客戶端實現,服務端需要先從NuGet安裝以下類庫:

Grpc.AspNetCore

Grpc.AspNetCore.Server

Grpc.Tools

服務端專案配置如下:

<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Grpc.AspNetCore" Version="2.60.0" />
<PackageReference Include="Grpc.AspNetCore.Server" Version="2.60.0" />
<PackageReference Include="Grpc.Tools" Version="2.60.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Protobuf Include="Protos\greet.proto" GrpcServices="Server" />
</ItemGroup>
</Project>
greet.proto 配置檔案內容如下,服務端和客戶端一致。

syntax = "proto3";

option csharp_namespace = "GrpcGreeter";

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;
}
客戶端專案配置:

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

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

需要從NuGet安裝如下類庫:

Grpc.AspNetCore

Grpc.Net.Client

Grpc.Tools

安裝 Grpc.Tools 後,在生成專案時,可以自動生成對應的Protobuf通訊類。

這裡還要把服務端的專案載入配置貼出來一下,主要是關於https的啟動配置

在這裡面

{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:64606",
"sslPort": 44331
}
},
"profiles": {
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7086;http://localhost:5193",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

程式碼實現
客戶端程式碼
using Grpc.Net.Client;
using GrpcGreeter;
using static GrpcGreeter.Greeter;

using var channel = GrpcChannel.ForAddress("https://localhost:7086", (new GrpcChannelOptions() { UnsafeUseInsecureChannelCallCredentials = true }));
var client = new GreeterClient(channel);
var reply = await client.SayHelloAsync(
new HelloRequest { Name = "GreeterClient" });
Console.WriteLine("Greeting: " + reply.Message);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
服務端程式碼
using Grpc.Core;
using GrpcGreeter;
using static GrpcGreeter.Greeter;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddGrpc();

var app = builder.Build();

// Configure the HTTP request pipeline.
app.MapGrpcService<GreeterService>();
app.MapGet("/", () => "Communication with gRPC endpoints must be made through a gRPC client.");

app.Run();

public class GreeterService : GreeterBase
{
public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
{
Console.WriteLine($"Request:{request.Name}");
return Task.FromResult(new HelloReply { Message = $"Hello this is rjcql's {request.Name}" });
}
}
呼叫示例
服務端控制檯輸出

客戶端控制檯輸出

專案目錄結構示意


原文連結:https://blog.csdn.net/rjcql/article/details/135890720

相關文章