环境
.net 8
vs2022
创建 gRPC 服务器
一定要勾选Https
安装Nuget包
<PackageReference Include="Google.Protobuf" Version="3.28.2" />
<PackageReference Include="Grpc.AspNetCore" Version="2.66.0" />
<PackageReference Include="Grpc.Net.Client" Version="2.66.0" />
<PackageReference Include="Grpc.Tools" Version="2.66.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
新建Protos文件夹,该文件下新建greet.proto
syntax = "proto3";
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply);
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
添加编译
<ItemGroup>
<Protobuf Include="Protos\greet.proto" GrpcServices="Server" />
</ItemGroup>
新建Service文件夹,该文件夹下新建GreeterService
using Grpc.Core;
namespace GrpcServer01.Service
{
public class GreeterService : Greeter.GreeterBase
{
private readonly ILogger<GreeterService> _logger;
public GreeterService(ILogger<GreeterService> logger)
{
_logger = logger;
}
public override Task<HelloReply> SayHello(HelloRequest request,
ServerCallContext context)
{
_logger.LogInformation("Saying hello to {Name}", request.Name);
return Task.FromResult(new HelloReply
{
Message = "Hello " + request.Name
});
}
}
}
修改Program.cs
using GrpcServer01.Service;
namespace GrpcServer01
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
//新增代码在这
builder.Services.AddGrpc();
var app = builder.Build();
//新增代码在这
app.MapGrpcService<GreeterService>();
app.MapGet("/", () => "Hello World!");
app.Run();
}
}
}
启动项目访问https://localhost:7006/
服务端创建成功
创建grpc客户端
安装nuget包
<ItemGroup>
<PackageReference Include="Google.Protobuf" Version="3.28.2" />
<PackageReference Include="Grpc.Net.Client" Version="2.66.0" />
<PackageReference Include="Grpc.Tools" Version="2.66.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
复制服务端Protos\greet.proto
到客户端
<ItemGroup>
<Protobuf Include="Protos\greet.proto" GrpcServices="Client" />
</ItemGroup>
修改Program.cs
internal class Program
{
static async Task Main(string[] args)
{
using var channel = GrpcChannel.ForAddress("https://localhost:7006");
var client = new Greeter.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();
}
}
客户端
服务端
参考
https://grpc.io/docs/languages/csharp/
https://blog.csdn.net/kevin_tech/article/details/120681720
https://learn.microsoft.com/zh-cn/aspnet/core/grpc/?view=aspnetcore-8.0
grpc详解
https://cloud.tencent.com/developer/article/1913513
https://protobuf.dev/overview/