nodejs grpc服务搭建丨技术开发分享录

nodejs grpc服务搭建

{{ detail.nickname }}

转载 翻译 {{ formatTime(detail.create_time) }} 字数 {{ detail.content && detail.content.length }} 阅读 {{ detail.read_num }} {{ formatTag(v) }}

"grpc官方文档:http://doc.oschina.net/grpc\n\n## 一、简介\n\ngRPC  是一个高性能、开源和通用的 RPC 框架,**面向移动和 HTTP/2 设计**。目前提供 C、Java 和 Go 语言版本,分别是:grpc, grpc-java, grpc-go. 其中 C 版本支持 C, C++, Node.js, Python, Ruby, Objective-C, PHP 和 C# 支持.\n\ngRPC 基于 HTTP/2 标准设计,带来诸如双向流、流控、头部压缩、单 TCP 连接上的多复用请求等特。这些特性使得其在移动设备上表现更好,更省电和节省空间占用。\n\n![](http://www.grpc.io/img/grpc_concept_diagram_00.png)\n\n## 二、示例\n\n目录结构\n\n```dir\n├─ grpc_test  \n    ├─ protos\n    ├─ ├─  HelloWorld.proto\n    ├─ greeter_server.js\n    ├─ greeter_client.js  \n    └─ package.json\n```\n\npackage.json\n\n```\n{\n  \"dependencies\": {\n    \"@grpc/proto-loader\": \"^0.5.5\",\n    \"grpc\": \"^1.24.3\"\n  }\n}\n```\n\n通过npm install安装依赖\n\n```cli\ngrpc> npm install\n```\n\n> protobuf语法:https://www.cnblogs.com/crazymakercircle/p/9937766.html\n\nprotos/HelloWorld.proto\n\n```\nsyntax = \"proto3\";\n\noption java_package = \"ex.grpc\";\noption objc_class_prefix = \"HSW\";\n\npackage helloworld;\n\n\nservice Greeter {\n  rpc sayHello (HelloRequest) returns (HelloReply) {}\n\n  rpc printAge (printAgeRequest) returns (printAgeReply) {}\n}\n\nmessage HelloRequest {\n  string name = 1;\n  string city = 2;\n}\n\nmessage HelloReply {\n  string message = 1;\n}\n\nmessage printAgeRequest {\n  string age = 1;\n}\n\nmessage printAgeReply {\n  string text = 1;\n}\n```\n\ngreeter_server.js\n\n```\nconst path = require(\"path\");\nconst grpc = require(\"grpc\");\nconst protoLoader = require(\"@grpc/proto-loader\");\n\n// 从 proto 文件加载服务描述符\nconst PROTO_PATH = path.resolve(__dirname, \"protos/HelloWorld.proto\");\nconst packageDefinition = protoLoader.loadSync(PROTO_PATH, {\n  keepCase: true,\n  longs: String,\n  enums: String,\n  defaults: true,\n  oneofs: true,\n});\nconst hello_proto = grpc.loadPackageDefinition(packageDefinition).helloworld;\n\n// 服务器的启动方法\n/*\n1、通过 Greeter 服务描述符创建一个 Server 构造函数。\n2、实现服务的方法。\n3、通过调用 Server 的构造函数以及方法实现去创建一个服务器的实例。\n4、用实例的 bind() 方法指定地址以及我们期望客户端请求监听的端口。\n5、调用实例的 start() 方法启动一个RPC服务器。\n*/\nfunction main() {\n  const server = new grpc.Server();\n  server.addService(hello_proto.Greeter.service, {\n    // sayHello的实现,调用call.request为protobuf文件的请求体,将返回体通过callback函数回传至客户端\n    sayHello(call, callback) {\n      try {\n        let data =\n          \"hello \" + call.request.name + \" and city is \" + call.request.city;\n        callback && callback(null, { message: data });\n      } catch (err) {\n        console.log(\"错误\");\n        callback && callback(err);\n      }\n    },\n    printAge(call, callback) {\n      try {\n        let text = \"current age is \" + call.request.age;\n        callback && callback(null, { text });\n      } catch (err) {\n        console.log(\"错误\");\n        callback && callback(err);\n      }\n    },\n  });\n  server.bind(\"127.0.0.1:50051\", grpc.ServerCredentials.createInsecure());\n  server.start();\n  console.log(\"server start......\");\n}\n\nmain();\n```\n\ngreeter_client.js\n\n```\nconst path = require(\"path\");\nconst grpc = require(\"grpc\");\nconst protoLoader = require(\"@grpc/proto-loader\");\n\nconst PROTO_PATH = path.resolve(__dirname, \"protos/HelloWorld.proto\");\nconst packageDefinition = protoLoader.loadSync(PROTO_PATH, {\n  keepCase: true,\n  longs: String,\n  enums: String,\n  defaults: true,\n  oneofs: true,\n});\n\nconst hello_proto = grpc.loadPackageDefinition(packageDefinition).helloworld;\n\nfunction main() {\n  console.log(\"client start.......\");\n  \n  // 调用 Greeter 的存根构造函数,指定服务器地址和端口。\n  const client = new hello_proto.Greeter(\n    \"127.0.0.1:50051\",\n    grpc.credentials.createInsecure()\n  );\n\n  // 调用存根上的方法,传入请求和回调函数\n  client.sayHello({ name: \"locy\", city: \"合肥\" }, (error, response) => {\n    if (error) {\n      console.log(error);\n      return;\n    }\n    console.log(\"Greeting: \", response.message);\n  });\n\n  client.printAge({ age: \"45\" }, (error, response) => {\n    if (error) {\n      console.log(error);\n      return;\n    }\n    console.log(\"Text is : \", response.text);\n  });\n}\n\nmain();\n```\n\n运行server命令\n\n```cli\ngrpc> node greeter_server.js\nserver start......\n```\n\n运行client命令\n\n```cli\ngrpc> node greeter_client.js\nclient start.......\nText is :  current age is 45\nGreeting:  hello locy and city is 合肥\n```\n\n相对于命令行还是看可视化的比较清爽舒服,现在市场上已经有相应的客户端工具,这里推荐BloomRPC软件\n下载地址:https://github.com/uw-labs/bloomrpc/releases\n选择:bloomrpc-setup-1.4.1.exe 下载安装\n\n使用:\n启动greeter_server.js服务后,在BloomRPC上导入HelloWorld.proto,然后配置好env即可,效果如下:\n\n![image.png](/images/articles/image20200805173624.png)\n\n> 注意:启动服务后不要在命令行面板选中,不然工具修改提交不响应"
PS:写作不易,如要转裁,请标明转载出处。

如果此篇对您有帮助,可小额赞助,以兹鼓励!

猜你想看