gRPC搭建使用方式

 gRpc 官網  連接 ide

新建服務端項目spa

在服務端內先編寫一個 .proto 文件code

greet.protoorm

syntax = "proto3";

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply);
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

服務端生成 .proto 代碼爲 C#   NutGet Install-Package Grpc.Tools server

  

找到tools 從裏面選擇本身電腦的版本blog

把 protoc.exe 、 grpc_csharp_plugin.exe 複製出來和 .proto 文件放在一塊兒rpc

編寫一個 .cmd 文件和 .proto 文件放在一塊兒,插入生成代碼的指令。(注意 greet.proto 這是 .proto 文件名)get

protoc -I . --csharp_out . --grpc_out . --plugin=protoc-gen-grpc=grpc_csharp_plugin.exe greet.proto   

點擊cmd 生成 會得到兩個C#文件。cmd

新建類GreeterServicestring

並在使用客戶端以前啓動(啓動服務端以前,要先排除與.Net 無關的.proto文件,否則直接運行會報錯的)

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
        });
    }  
}
 class Program
 {

     const int Port = 2020;

     static void Main(string[] args)
     {
         Server server = new Server
        {
            Services = { Greeter.BindService(new GreeterService()) },
            Ports = { new ServerPort("127.0.0.1", 2020, ServerCredentials.Insecure) }
         };
         server.Start();
         Console.WriteLine("127.0.0.1");
         Console.WriteLine("GrpcService server listening on port " + Port);
         Console.WriteLine("任意鍵退出...");
         Console.ReadKey();
     }
}

新建控制檯客戶端項目

客戶端調用服務端

namespace gRPCClient
{
    class Program
    {
        static void Main(string[] args)
        {
      
            // The port number(5001) must match the port of the gRPC server.
            Channel channel = new Channel("127.0.0.1", 2020, ChannelCredentials.Insecure);
            var client = new Greeter.GreeterClient(channel).WithHost("127.0.0.1");
            
            try
            {
                var reply = client.SayHelloAsync(new HelloRequest { Name = "Zhang San" });
                Console.WriteLine("來自" + reply.ResponseAsync.Result);

                channel.ShutdownAsync().Wait();
                Console.WriteLine("Greeting: " + reply.ResponseAsync.Result);
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
            }
            catch (Exception ex)
            {

                throw ex;
            }
 
           
        }
    }
}
相關文章
相關標籤/搜索