写在前面
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}" });
}
}