C# 實現 gRPC 服務和調用

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章