前端JS调用.Net 6 Grpc服务
1.准备工作
1.Protocol Buffers
下载地址:https://github.com/protocolbuffers/protobuf/releases
需要注册环境变量
- PROTOC_HOME -> D:\Developer\protoc\bin 【你自己的二进制目录】
- Path -> 追加 %PROTOC_HOME%
2.Protobuf Javascript[插件]
下载地址:https://github.com/protocolbuffers/protobuf-javascript/releases
3.protoc-gen-grpc-web[插件]
下载地址:https://github.com/grpc/grpc-web/releases
4.grpcwebproxy[前端代理转发工具,可使用Envoy替代]
2.官方js客户端案例
1.克隆
git clone https://github.com/grpc/grpc-web.git
2.定位到/net/grpc/gateway/examples/helloworld,执行命令生成grpc客户端文件
cd ./net/grpc/gateway/examples/helloworld
protoc -I=./ ./helloworld.proto \
--plugin=protoc-gen-grpc-web=D:/Developer/protoc/bin/protoc-gen-grpc-web.exe \
--plugin=protoc-gen-js=D:/Developer/protobufjavascript/bin/protoc-gen-js.exe \
--js_out=import_style=commonjs:./ \
--grpc-web_out=import_style=commonjs,mode=grpcwebtext:./
3.编译客户端
npm install
npx webpack client.js
3.创建.Net 6 Grpc服务端
1.在文件夹中执行命令使用grpc模版创建项目
dotnet new grpc -o grpc-service-web
2.运行如下命令添加对 Grpc.AspNetCore.Web 包的引用
cd grpc-service-web
dotnet add grpc-service-web.csproj package Grpc.AspNetCore.Web
3.添加grpc相关配置
using grpc_service_web.Services;
var builder = WebApplication.CreateBuilder(args);
// Additional configuration is required to successfully run gRPC on macOS.
// For instructions on how to configure Kestrel and gRPC clients on macOS, visit https://go.microsoft.com/fwlink/?linkid=2099682
// Add services to the container.
builder.Services.AddGrpc();
builder.Services.AddCors(o => o.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.WithExposedHeaders("Grpc-Status", "Grpc-Message", "Grpc-Encoding", "Grpc-Accept-Encoding");
}));
//项目是跑在webApi的项目中,所以还要配置内核去监听另一个端口才能接收并处理gRPC的请求
builder.WebHost.ConfigureKestrel(options =>
{
//webApi监听端口
options.Listen(System.Net.IPAddress.Any, 5157, listenOptions =>
{
listenOptions.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http1AndHttp2;
});
//grpc监听端口
options.Listen(System.Net.IPAddress.Any, 5158, listenOptions =>
{
listenOptions.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http2;
});
});
var app = builder.Build();
// Configure the HTTP request pipeline.
app.MapGrpcService<HelloWorldService>();
app.UseGrpcWeb(new GrpcWebOptions() { DefaultEnabled = true });
app.UseCors();
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();
4.将js客户端的proto文件拷贝到.net项目中
5.右键编辑项目文件,将 .proto 文件添加到 项目组
<ItemGroup>
<Protobuf Include="Protos\helloworld.proto" GrpcServices="Server" />
</ItemGroup>
6.右键proto文件在属性中选择生成模式
7.继承proto生成的服务端代码并修改
using Grpc.Core;
namespace grpc_service_web.Services;
public class HelloWorldService : grpc_service_web.Greeter.GreeterBase
{
public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
{
return Task.FromResult<HelloReply>(new HelloReply(){Message = $"coreqi {request.Name}" });
}
public override Task SayRepeatHello(RepeatHelloRequest request, IServerStreamWriter<HelloReply> responseStream, ServerCallContext context)
{
return Task.FromResult<Task>(
responseStream.WriteAsync(new HelloReply() { Message = $"coreqi {request.Name}" })
);
}
}
4.运行grpcwebproxy前端代理转发工具,注意JS客户端请求的转发地址及.NET服务端运行的GRPC端口
grpcwebproxy-v0.15.0-win64.exe --allow_all_origins --backend_addr=localhost:5158 --run_tls_server=false --server_http_debug_port=8080 --allow_all_origins=true
5.使用Http-server或Nginx运行JS客户端,查看效果