假如有一个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;
}
项目需要根据proto文件生成js文件和service文件
这里需要先下载protoc.exe执行程序,下载地址:https://github.com/protocolbuffers/protobuf/releases
选择protoc-3.12.4-win64.zip下载,安装完成后需要将bin目录添加到环境变量中,然后执行命令
> protoc --version
libprotoc 3.12.4
再在项目中通过npm安装ts-protoc-gen
[project]> cnpm i ts-protoc-gen -S
接着进入到存放proto文件的目录,执行以下命令
protos> protoc --plugin="protoc-gen-ts=/nodejs/experiment/vue-test/node_modules/ts-protoc-gen/bin/protoc-gen-ts.cmd" --ts_out="service=grpc-web:./" ./HelloWorld.proto
即可生成下面四个文件:
HelloWorld_pb.js
HelloWorld_pb_service.js
HelloWorld_pb.d.ts
HelloWorld_pb_service.d.ts
在vue中使用
import { GreeterClient } from "@/assets/protos/HelloWorld_pb_service.js";
import { HelloRequest } from "@/assets/protos/HelloWorld_pb.js";
const helloRequest = new HelloRequest();
const client = new GreeterClient('http://127.0.0.1:50051');
client.sayHello(helloRequest, {"Content-Type": "application/grpc-web+proto"}, (err, response) => {
console.log(err, response)
});
或
需要安装
> npm i @improbable-eng/grpc-web google-protobuf -S
import { grpc } from "@improbable-eng/grpc-web";
import { Greeter } from "@/assets/protos/HelloWorld_pb_service.js";
import { HelloRequest } from "@/assets/protos/HelloWorld_pb.js";
const helloRequest = new HelloRequest();
grpc.unary(Greeter.sayHello, {
request: helloRequest,
host: "http://127.0.0.1:50051",
onMessage: (message) => {
console.log(message.toObject());
},
onEnd: (res) => {
const { status, statusMessage, headers, message, trailers } = res;
if (status === grpc.Code.OK && message) {
console.log("all ok. got book: ", message.toObject());
}
},
});