pb文件生成java类,根据proto文件生成pb和pb_service文件

假如有一个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-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());

}

},

});

  • 0
    点赞
  • 0
    收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:游动-白 设计师:我叫白小胖 返回首页
评论
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值