.net core 3.0新增加功能
创建grpg服务
一、服务端
using System.Threading.Tasks; using Grpc.Core; using Microsoft.Extensions.Logging; namespace GrpcGreeter { 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) { return Task.FromResult(new HelloReply { Message = "Hello " + request.Name }); } } }
二、客户端
1.Nuget包
Grpc.Net.Client 包含 .NET Core 客户端
Google.Protobuf 包含适用于 C# 的 Protobuf 消息
Grpc.Tools 包含适用于 Protobuf 文件的 C# 工具支持。 运行时不需要工具包,因此依赖项标记为 PrivateAssets="All"
2.创建Protos文件夹,从 gRPC Greeter 服务将 Protosgreet.proto 文件复制到 gRPC 客户端项目
3.工程文件添加
<ItemGroup> <Protobuf Include="Protosgreet.proto" GrpcServices="Client" /> </ItemGroup>
4.Program.cs
using System; using System.Threading.Tasks; using GrpcGreeter; using Grpc.Net.Client; namespace GrpcGreeterClient { class Program { static async Task Main(string[] args) { var channel = GrpcChannel.ForAddress("https://localhost:5001"); 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(); } } }