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


這里還要把服務(wù)端的項(xiàng)目加載配置貼出來一下,主要是關(guān)于https的啟動(dòng)配置

在這里面
{
"$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"
}
}
}
}代碼實(shí)現(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();
服務(wù)端代碼
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)用示例
服務(wù)端控制臺(tái)輸出


客戶端控制臺(tái)輸出

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

以上就是C#實(shí)現(xiàn)gRPC服務(wù)和調(diào)用示例詳解的詳細(xì)內(nèi)容,更多關(guān)于C# gRPC服務(wù)和調(diào)用的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#中實(shí)現(xiàn)可變參數(shù)實(shí)例
這篇文章主要介紹了C#中實(shí)現(xiàn)可變參數(shù)實(shí)例,本文演示使用params 實(shí)現(xiàn)可變數(shù)量的參數(shù),并且這些參數(shù)的類型可以不同,需要的朋友可以參考下2015-01-01
C#實(shí)現(xiàn)六大設(shè)計(jì)原則之依賴倒置原則
這篇文章介紹了C#實(shí)現(xiàn)六大設(shè)計(jì)原則之依賴倒置原則的方法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-02-02
C#如何在窗體程序中操作數(shù)據(jù)庫數(shù)據(jù)
這篇文章主要介紹了C#如何在窗體程序中操作數(shù)據(jù)庫數(shù)據(jù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04

