C#實現(xiàn)gRPC服務和調(diào)用示例詳解
寫在前面
gRPC 是一種與語言無關(guān)的高性能遠程過程調(diào)用 (RPC) 框架。
主要優(yōu)點如下:
1.高性能輕量化。
2.協(xié)議優(yōu)先的 API 定義模式,默認使用協(xié)議緩沖區(qū),允許與語言無關(guān)的實現(xiàn)。
3.可用于多種語言的工具,以生成強類型服務器和客戶端。
4.支持客戶端、服務器和雙向流式處理調(diào)用。
5.使用 Protobuf 二進制序列化減少對網(wǎng)絡的使用。
gRPC 服務可以托管在 ASP.NET Core 上。 這些服務與日志記錄、依賴關(guān)系注入 (DI)、身份驗證和授權(quán)等 ASP.NET Core 功能完全集成。
本文示例包含服務端實現(xiàn)和客戶端實現(xiàn),服務端需要先從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 配置文件內(nèi)容如下,服務端和客戶端一致。
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通訊類。


這里還要把服務端的項目加載配置貼出來一下,主要是關(guān)于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"
}
}
}
}代碼實現(xiàn)
客戶端代碼
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}" });
}
}調(diào)用示例
服務端控制臺輸出


客戶端控制臺輸出

項目目錄結(jié)構(gòu)示意

以上就是C#實現(xiàn)gRPC服務和調(diào)用示例詳解的詳細內(nèi)容,更多關(guān)于C# gRPC服務和調(diào)用的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#/VB.NET?將Word與Excel文檔轉(zhuǎn)化為Text
這篇文章主要介紹了C#/VB.NET?將Word與Excel文檔轉(zhuǎn)化為Text,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下2022-08-08
C#更新文本框textbox數(shù)據(jù)同時刪除舊數(shù)據(jù)問題
這篇文章主要介紹了C#更新文本框textbox數(shù)據(jù)同時刪除舊數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-04-04
C#獲取變更過的DataTable記錄的實現(xiàn)方法
這篇文章主要介紹了C#獲取變更過的DataTable記錄的實現(xiàn)方法,對初學者很有學習借鑒價值,需要的朋友可以參考下2014-08-08

