您的位置:首页 > Web前端 > AngularJS

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

2021-01-08 11:19 921 查看

AspNetCore配置grpc服务端

新建一个Demo项目:

GrpcStartup
, 目录结构如下图:

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客户端

生成angular项目(略);

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

使用

protoc
命令生成typescript版本的客户端代码, 生成代码前, 需要先下载后
protoc.exe
protoc-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个文件

客户端代码

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

  • google-protobuf
  • grpc-web

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

greeter.service.ts
import { Injectable } from '@angular/core';
import { GreeterClient } from './Gree
1308
terServiceClientPb';
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
, 可以在浏览器控制台看到结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐