ASP.net Core 的gRPC Service应用

通过[Greeter示例](https://github.com/grpc/grpc-dotnet/tree/master/examples/Greeter),来演示gRPC Service

Server 在Ubuntu V20.04; Client 在Windows CMD运行。

  • PowerShell v5.1
  • IDE: VS2019 Community(v16.9)/VS Code(docker extension)
  • VM: VBox(v6.1)

接口文件说明

Protos/greet.proto

现版本(v16.9)已可以自动生成

定义service

service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

定义message

  • request
message HelloRequest {
  string name = 1;
}
  • response
message HelloReply {
  string message = 1;
}

server

Create

VS2019

VS2019 pre1 注意:服务器需要docker支持! VS2019 pre2

VS2019 pre3

VS code

dotnet new grpc -o GreeterServer

add docke file

  • View -> Command Palette(Ctrl+Shift+P)
  • Enter: Docker fi
  • choice1: Add Docker Files to Workspace…
  • choice2: .NET: ASP.NET Core
  • choice3: Linux
  • Enter: 80
  • choice4: No(Include compose file)

修改Dockerfile

  • 移出Ubuntu版本信息(-focal)

focal: Ubuntu 20.04

  • 移出调试URL

ENV ASPNETCORE_URLS=http://+:80

实现的service

VS2019/vs code自动生成

public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
{
    return Task.FromResult(new HelloReply
    {
        Message = "Hello " + request.Name
    });
}

添加SSL支持1

Program.cs

更改生成的Code:

 webBuilder.UseStartup<Startup>();

变更:

webBuilder.UseStartup<Startup>().ConfigureKestrel(options =>
               {
                   options.Listen(IPAddress.Any, 5001, listenOptions =>
                   {
                       listenOptions.Protocols = HttpProtocols.Http2;
                   });
               });

client

建一个Console应用程序,来测试gRPC服务。

Create

vs2019

主要的NuGet: VS2019 NuGet1

Install-Package Grpc.Core" -Version 2.41.0

其他NuGet:

Install-Package Google.Protobuf -Version 3.18.0
Install-Package Grpc.Net.Client -Version 2.39.0
Install-Package Grpc.Tools -Version 2.41.0

vs code

dotnet new console -o GreeterClient

NuGet

dotnet add GreeterClient.csproj package Grpc.Net.Client
dotnet add GreeterClient.csproj package Google.Protobuf
dotnet add GreeterClient.csproj package Grpc.Tools

增加Proto2

GreeterClient.csproj

<ItemGroup>
  <Protobuf Include="Protos\greet.proto" GrpcServices="Client" />
</ItemGroup>

test程序3

Program.cs

static async Task Main(string[] args)
{
    // The port number(5001) must match the port of the gRPC server.
    using 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();
}

Test picture

cmd vmware cmd

Reference