https://mp.weixin.qq.com/s/syZx-fIs_mTT6-UoLcEhkA

gRPC JSON转码
gRPC JSON 转码允许浏览器应用调用 gRPC 服务,就像它们是使用 JSON 的 RESTful API 一样。

浏览器应用不需要生成 gRPC 客户端或了解 gRPC 的任何信息。

通过使用 HTTP 元数据注释 .proto 文件,可从 gRPC 服务自动创建 RESTful API。

使应用可以同时支持 gRPC 和 JSON Web API,而无需重复为两者生成单独的服务。

OpenAPI与gRPC Server
OpenAPI(以前称为 Swagger)是一个与语言无关的规范,用于描述 API。gRPC JSON 转码支持从转码 REST ful的 API 生成 OpenAPI。

实现Server端
通过VS新增GRPC Server,新增nuget包


<ItemGroup>
  <PackageReference Include="Grpc.AspNetCore" Version="2.49.0" />
  <PackageReference Include="Microsoft.AspNetCore.Grpc.JsonTranscoding" Version="7.0.0" />
  <PackageReference Include="Microsoft.AspNetCore.Grpc.Swagger" Version="0.3.0" />
</ItemGroup>

为api生成用于OpenAPI的注释XML文件,在Server.csproj文件中新增以下配置


<GenerateDocumentationFile>true</GenerateDocumentationFile>
Server的Program.cs中,开启JSON转码与Swagger

var builder = WebApplication.CreateBuilder(args);

// 开启JSON转码
builder.Services.AddGrpc().AddJsonTranscoding();

// 配置Swagger
builder.Services.AddGrpcSwagger();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "gRPC transcoding", Version = "v1" });
    var filePath = Path.Combine(System.AppContext.BaseDirectory, "GrpcService4.xml");
    c.IncludeXmlComments(filePath);
    c.IncludeGrpcXmlComments(filePath, includeControllerXmlComments: true);
});

var app = builder.Build();

//开启Swagger
app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});

app.MapGrpcService<GreeterService>();
app.MapGet("/", () => "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");

app.Run();

下载GRPC JSON转码依赖的proto文件

https://github.com/dotnet/aspnetcore/blob/main/src/Grpc/JsonTranscoding/test/testassets/Sandbox/google/api/http.proto

https://github.com/dotnet/aspnetcore/blob/main/src/Grpc/JsonTranscoding/test/testassets/Sandbox/google/api/annotations.proto

并将文件放到项目的google/api/文件夹中。

修改greet.proto文件,通过option开启http选项,以一个get方法和一个post方法举例


syntax = "proto3";

import "google/api/annotations.proto";

option csharp_namespace = "GrpcService4";

package greet;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply){
     option (google.api.http) = {
      get: "/v1/greeter/{name}"
    };
  };

    // Sends a greeting
  rpc SayHelloPost (HelloRequestPost) returns (HelloReply){
     option (google.api.http) = {
      post: "/v1/greeter/post",
      body:"data"
    };
  };
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The request message containing the user's name.
message HelloRequestPost {
  HelloRequestPostData data = 1;
}

message HelloRequestPostData{
    string name = 1;
    string gender = 2;
}

// The response message containing the greetings.
message HelloReply {
  string message = 1;
}

然后实现Server


using Grpc.Core;
using GrpcService4;

namespace GrpcService4.Services
{
    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
            });
        }


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

至此server的json转码开启完成,运行服务,访问swagger,即可尝试http方式请求

图片

在支持http方式的请求的情况下,同时支持grpc请求。

实现Client端
新增控制台项目,添加以下nuget

<ItemGroup>
  <PackageReference Include="Google.Protobuf" Version="3.21.9" />
  <PackageReference Include="Grpc.Net.Client" Version="2.49.0" />
  <PackageReference Include="Microsoft.AspNetCore.Grpc.JsonTranscoding" Version="7.0.0" />
  <PackageReference Include="Grpc.Tools" Version="2.50.0">
    <PrivateAssets>all</PrivateAssets>
    <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
  </PackageReference>
</ItemGroup>

包含与server端相同的proto文件


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

尝试请求Server

static async Task Main(string[] args)
{
    using var channel = GrpcChannel.ForAddress("https://localhost:7167");
    var client = new Greeter.GreeterClient(channel);
    var reply = await client.SayHelloAsync(new HelloRequest { Name = "GreeterClient" });
    Console.WriteLine("Greeting: " + reply.Message);

    var replyPost = await client.SayHelloPostAsync(new HelloRequestPost { Data = new HelloRequestPostData { Name = "111" } });
    Console.WriteLine("Greeting: " + replyPost.Message);
    Console.WriteLine("Press any key to exit...");
    Console.ReadKey();
}

source code: https://github.com/cysnet/grpc-json-transcoding

文档更新时间: 2022-11-11 13:52   作者:admin