NodeJS GRPC簡單的示例詳解
更新時間:2024年10月16日 09:38:04 作者:田猿筆記
本文介紹了如何使用NodeJS GRPC,包括.proto文件的定義、客戶端和服務器的實現(xiàn),首先,創(chuàng)建.proto文件定義服務和消息,然后實現(xiàn)客戶端greeter_client.js文件,最后運行服務器和客戶端,通過這篇文章,你可以快速掌握NodeJS GRPC的基礎使用方法
1. 定義 .proto
文件
首先,創(chuàng)建一個 .proto
文件,定義服務和消息:
syntax = "proto3"; package helloworld; service Greeter { rpc SayHello (HelloRequest) returns (HelloReply) {} rpc SayHelloAgain (HelloRequest) returns (HelloReply) {} } message HelloRequest { string name = 1; } message HelloReply { string message = 1; }
### 2. 實現(xiàn)服務器 創(chuàng)建 `greeter_server.js` 文件,包含服務的實現(xiàn): ```javascript const grpc = require('@grpc/grpc-js'); const protoLoader = require('@grpc/proto-loader'); const packageDefinition = protoLoader.loadSync('helloworld.proto', { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true }); const helloProto = grpc.loadPackageDefinition(packageDefinition).helloworld; function sayHello(call, callback) { callback(null, { message: 'Hello ' + call.request.name }); } function sayHelloAgain(call, callback) { callback(null, { message: 'Hello again, ' + call.request.name }); } function main() { const server = new grpc.Server(); server.addService(helloProto.Greeter.service, { sayHello: sayHello, sayHelloAgain: sayHelloAgain }); server.bindAsync('0.0.0.0:50051', grpc.ServerCredentials.createInsecure(), () => { server.start(); }); } main();
3. 實現(xiàn)客戶端
創(chuàng)建 greeter_client.js
文件,包含客戶端的實現(xiàn):
const grpc = require('@grpc/grpc-js'); const protoLoader = require('@grpc/proto-loader'); const packageDefinition = protoLoader.loadSync('helloworld.proto', { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true }); const helloProto = grpc.loadPackageDefinition(packageDefinition).helloworld; function main() { const client = new helloProto.Greeter('localhost:50051', grpc.credentials.createInsecure()); client.sayHello({ name: 'World' }, (err, response) => { if (err) console.error(err); else console.log('Greeting:', response.message); }); client.sayHelloAgain({ name: 'World' }, (err, response) => { if (err) console.error(err); else console.log('Greeting:', response.message); }); } main();
4. 運行服務器和客戶端
確保你已經(jīng)安裝了所有必要的依賴:
npm install @grpc/grpc-js @grpc/proto-loader
然后,分別運行服務器和客戶端:
node greeter_server.js node greeter_client.js
到此這篇關于NodeJS GRPC簡單的例子的文章就介紹到這了,更多相關NodeJS GRPC例子內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
node.js中的querystring.unescape方法使用說明
這篇文章主要介紹了node.js中的querystring.unescape方法使用說明,本文介紹了querystring.unescape的方法說明、語法、接收參數(shù)、使用實例和實現(xiàn)源碼,需要的朋友可以參考下2014-12-1210個Node.js庫幫助你優(yōu)化代碼和簡化開發(fā)
這篇文章主要介紹了10個Node.js庫幫助你優(yōu)化代碼和簡化開發(fā),其中包括處理數(shù)組、對象、字符串庫Lodash,緩存數(shù)據(jù)處理庫Node-cache,解析、操作和格式化日期和時間庫Moment.js,Redis操作庫,發(fā)送電子郵件庫Nodemailer2023-05-05切換到淘寶最新npm鏡像源的全面指南(支持 Windows、macOS 和多種 Linux
在開發(fā)過程中,npm 是前端開發(fā)者不可或缺的工具,但對于國內(nèi)的開發(fā)者來說,npm 官方源在下載速度上存在一定的瓶頸,本文將詳細介紹如何在 Windows、macOS 以及各類 Linux 發(fā)行版上切換到淘寶的 npm 鏡像源,需要的朋友可以參考下2025-03-03