.Net Core框架下实现Grpc客户端和服务端

一、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="Protos\greet.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();
        }
    }
复制代码

 

posted @   天众师兄  阅读(172)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示