一、Grpc服务端
1、新建.Net core框架下Grpc服务
2、修改launchsettings.json
{ "profiles": { "GrpcServer": { "commandName": "Project", "dotnetRunMessages": "true", "launchBrowser": false, "applicationUrl": "http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
3、修改greet.proto文件
syntax = "proto3"; option csharp_namespace = "MyGrpcServer"; package MyGrpc; // The greeting service definition. service TestGrpc { // Sends a greeting rpc TestSay (TestRequest) returns (TestReply); } // The request message containing the user's name. message TestRequest { string name = 1; } // The response message containing the greetings. message TestReply { string message = 1; }
4、修改GreeterService.cs
public class GreeterService : TestGrpc.TestGrpcBase { private readonly ILogger<GreeterService> _logger; public GreeterService(ILogger<GreeterService> logger) { _logger = logger; } public override Task<TestReply> TestSay(TestRequest request, ServerCallContext context) { Console.WriteLine($"接收到{request.Name}的消息"); return Task.FromResult(new TestReply { Message = "Hello " + request.Name }); } }
5、修改appsettings.json
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "Urls": "http://localhost:5000", "Kestrel": { "EndpointDefaults": { "Protocols": "Http2" } } }
二、Grpc客户端
1、新建.Net Core 控制台应用程序
2、NuGet包下载安装
Grpc.Net.Client
Google.ProtoBuf
Grpc.Tools
3、新建Protos文件夹,将服务端的greet.proto复制到该文件夹下,修改greet.proto
syntax = "proto3"; option csharp_namespace = "MyGrpcClient"; package MyGrpc; // The greeting service definition. service TestGrpc { // Sends a greeting rpc TestSay (TestRequest) returns (TestReply); } // The request message containing the user's name. message TestRequest { string name = 1; } // The response message containing the greetings. message TestReply { string message = 1; }
4、修改GrpcClient.csproj文件,添加一下代码
<ItemGroup> <Protobuf Include="Protosgreet.proto" GrpcServices="Client" /> </ItemGroup>
5、修改Program.cs
class Program { static async Task Main(string[] args) { using var channel = GrpcChannel.ForAddress("http://localhost:5000"); var client = new TestGrpc.TestGrpcClient(channel); var ret = await client.TestSayAsync(new TestRequest { Name = "MyTestClient" }); Console.WriteLine("MyTestGrpc: " + ret.Message); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } }