记angular和asp.net使用grpc进行通信

AspNetCore配置grpc服务端

新建一个Demo项目: GrpcStartup, 目录结构如下图:

记angular和asp.net使用grpc进行通信

GrpcStartup.GrpcServices需要安装下面的依赖

<PackageReference Include="Google.Protobuf" Version="3.14.0" />
<PackageReference Include="Grpc.AspNetCore" Version="2.34.0" />
<PackageReference Include="Grpc.AspNetCore.Web" Version="2.34.0" />
<PackageReference Include="Grpc.Net.Client" Version="2.34.0" />
<PackageReference Include="Grpc.Tools" Version="2.34.0">
    <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    <PrivateAssets>all</PrivateAssets>
</PackageReference>

编写protobuf

DotnetVersionReply.proto
syntax = "proto3";
import "google/protobuf/any.proto";

option csharp_namespace = "GrpcStartup.GrpcServices";

message DotnetVersionReply {
  string version = 1;
  string environment = 2;
}
Greeter.proto
syntax = "proto3";
import "google/protobuf/any.proto";
import "Protos/DotnetVersionReply.proto";

service Greeter {
  rpc GetDotnetEnvironment(google.protobuf.Any) returns (DotnetVersionReply);
}

protobuf写好后, 需要再.csproj中引入对应的文件

<ItemGroup>
    <Protobuf Include=".\Protos\*.proto" GrpcServices="server" />
</ItemGroup>

接下来build项目, 会生成相关代码, 这个例子中会有个一个 Greeter.GreeterBase 的抽象类被生成, 我们需要继承它编写我们的业务代码

GreeterRpcService.cs

public class GreeterRpcService: Greeter.GreeterBase
{
    public override Task<DotnetVersionReply> GetDotnetEnvironment(Any request, ServerCallContext context)
    {
        string os = Environment.OSVersion.VersionString;
        string dotnetVersion = Environment.Version.ToString();
        return Task.FromResult(new DotnetVersionReply
        {
            Environment = os,
            Version = dotnetVersion
        });
    }
}

修改Startup类, 配置Grpc

Startup.ConfigureServices

services.AddGrpc();
// 允许grpc-web
services.AddCors(o => o.AddPolicy("AllowGrpc", builder =>
{
    builder.AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader()
        .WithExposedHeaders("Grpc-Status", "Grpc-Message", "Grpc-Encoding", "Grpc-Accept-Encoding");
}));

Startup.Configure

app.UseRouting();

app.UseGrpcWeb(new GrpcWebOptions
{
    // 允许grpc-web
    DefaultEnabled = true
});
// 允许grpc-web
app.UseCors();

app.UseEndpoints(endpoints =>
{
    endpoints.MapGrpcService<GreeterRpcService>()
        .RequireCors("AllowGrpc");
    endpoints.MapRazorPages();
});

使用grpcui测试服务

grpcui是一个命令行工具, 运行它会打开一个网页, 下载链接

项目中支持grpcui需要配置一下

安装依赖: Grpc.AspNetCore.Server.Reflection

配置服务: services.AddGrpcReflection();

运行grpcui: C:\Users\laggage\Desktop\apps\grpcui_1.1.0_windows_x86_64> .\grpcui.exe localhost:5001

记angular和asp.net使用grpc进行通信

配置angular客户端

生成angular项目(略);

从protobuf文件生成js客户端代码

使用protoc命令生成typescript版本的客户端代码, 生成代码前, 需要先下载后 protoc.exeprotoc-gen-grpc-web 并将他们添加到环境变量下, 添加好后重启一下电脑让环境变量生效

C:\Users\laggage\Documents\coding\projects\GrpcStartup> protoc.exe -I. .\Greeter.proto --grpc-web_out=import_style=commonjs,mode=grpcwebtext:. --proto_path .

这个命令会生成3个文件

记angular和asp.net使用grpc进行通信

客户端代码

接下来编写客户端代码即可, 编写前需要先安装npm包

  • google-protobuf
  • grpc-web

然后写一个angular服务, 调用protobuf中定义的方法

greeter.service.ts
import { Injectable } from ‘@angular/core‘;
import { GreeterClient } from ‘./GreeterServiceClientPb‘;
import { HelloRequest, DotnetVersionReplay } from ‘./Greeter_pb‘;
import * as google_protobuf_any_pb from ‘google-protobuf/google/protobuf/any_pb‘;

@Injectable({
  providedIn: ‘root‘
})
export class GreeterService {
  static greeterService = new GreeterClient(‘https://localhost:5001‘);

  constructor() {
  }

  getDotnetVersion() {
    GreeterService.greeterService.getDotnetEnvironment(new google_protobuf_any_pb.Any(), {}, (err, res: DotnetVersionReplay) => {
      const version = res.getVersion();
      const env = res.getEnvironment();
      console.log(err, res);
      console.log(`env: ${env}, version: ${version}`);
    });
  }
}

AppComponent中注入这个服务并调用getDotnetVersion, 可以在浏览器控制台看到结果

记angular和asp.net使用grpc进行通信

记angular和asp.net使用grpc进行通信

上一篇:使用MathNet.Numerics库构造矩阵并初始化时,编译器报错“this方法没有任何重载采用"1"个参数”


下一篇:前端基础之CSS(第二天)