关于前端:protocgengrpcweb使用

29次阅读

共计 1682 个字符,预计需要花费 5 分钟才能阅读完成。

原文链接:http://fenxianglu.cn/article/246

grpc-web 阐明文档:https://www.npmjs.com/package…

gRPC 最后由谷歌开发,是一个高性能近程过程调用框架,基于 HTTP/2 实现。但因为浏览器没有间接裸露 HTTP/2,所以 Web 应用程序不能间接应用 gRPC。gRPC- Web 是一个标准化协定,它解决了这个问题,能够在浏览器中应用 gRPC。

protoc-gen-grpc-web 是用来生成 web js 文件的工具

下地地址:https://github.com/grpc/grpc-…

抉择:protoc-gen-grpc-web-1.2.0-windows-x86_64.exe 即可

下载实现后改名并挪动到我的项目里,示例是和寄存 proto 文件一起的

protoc-gen-grpc-web 依赖 protoc,所以还须要下载 protoc.exe 执行程序,下载地址:https://github.com/protocolbu…

抉择:protoc-3.12.4-win64.zip,下载安装实现后须要 将 bin 目录增加到环境变量中,而后执行命令

> protoc --version
libprotoc 3.12.4

以上筹备好后,再进入到寄存 proto 文件目录,执行以下代码

> protoc -I=./ ./HelloWorld.proto --js_out=import_style=commonjs:./ --plugin=protoc-gen-grpc=./protoc-gen-grpc-web.exe  --grpc-web_out=import_style=commonjs,mode=grpcwebtext:./

会生成以下两个文件:

HelloWorld_pb.js
HelloWorld_grpc_web_pb.js

在应用的时候还须要 npm 装置 grpc-web

> cnpm i grpc-web -S

具体如何应用,请看下面的 grpc-web 阐明文档

HelloWorld.proto 文件

syntax = "proto3";

option java_package = "ex.grpc";
option objc_class_prefix = "HSW";

package helloworld;


service Greeter {rpc sayHello (HelloRequest) returns (HelloReply) {}

  rpc printAge (printAgeRequest) returns (printAgeReply) {}}

message HelloRequest {
  string name = 1;
  string city = 2;
}

message HelloReply {string message = 1;}

message printAgeRequest {string age = 1;}

message printAgeReply {string text = 1;}

在 vue 中应用

import {GreeterClient} from '@/assets/protos/HelloWorld_grpc_web_pb.js';
import {HelloRequest} from '@/assets/protos/HelloWorld_pb.js';

const client = new GreeterClient('http://127.0.0.1:50051');

const helloRequest = new HelloRequest();
helloRequest.setCity('北京');
 
const metadata = {"Content-Type": "application/grpc-web+proto"};
 
client.sayHello(helloRequest, metadata, (err, response) => {console.log(err, response);
});

参考链接:

  • https://blog.csdn.net/Rsoftwa…
  • https://www.infoq.cn/article/…

正文完
 0