NodeJS GRPC簡單的示例詳解
1. 定義 .proto
文件
首先,創(chuàng)建一個(gè) .proto
文件,定義服務(wù)和消息:
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. 實(shí)現(xiàn)服務(wù)器 創(chuàng)建 `greeter_server.js` 文件,包含服務(wù)的實(shí)現(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. 實(shí)現(xiàn)客戶端
創(chuàng)建 greeter_client.js
文件,包含客戶端的實(shí)現(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. 運(yùn)行服務(wù)器和客戶端
確保你已經(jīng)安裝了所有必要的依賴:
npm install @grpc/grpc-js @grpc/proto-loader
然后,分別運(yùn)行服務(wù)器和客戶端:
node greeter_server.js node greeter_client.js
到此這篇關(guān)于NodeJS GRPC簡單的例子的文章就介紹到這了,更多相關(guān)NodeJS GRPC例子內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
node.js中的querystring.unescape方法使用說明
這篇文章主要介紹了node.js中的querystring.unescape方法使用說明,本文介紹了querystring.unescape的方法說明、語法、接收參數(shù)、使用實(shí)例和實(shí)現(xiàn)源碼,需要的朋友可以參考下2014-12-1210個(gè)Node.js庫幫助你優(yōu)化代碼和簡化開發(fā)
這篇文章主要介紹了10個(gè)Node.js庫幫助你優(yōu)化代碼和簡化開發(fā),其中包括處理數(shù)組、對(duì)象、字符串庫Lodash,緩存數(shù)據(jù)處理庫Node-cache,解析、操作和格式化日期和時(shí)間庫Moment.js,Redis操作庫,發(fā)送電子郵件庫Nodemailer2023-05-05切換到淘寶最新npm鏡像源的全面指南(支持 Windows、macOS 和多種 Linux
在開發(fā)過程中,npm 是前端開發(fā)者不可或缺的工具,但對(duì)于國內(nèi)的開發(fā)者來說,npm 官方源在下載速度上存在一定的瓶頸,本文將詳細(xì)介紹如何在 Windows、macOS 以及各類 Linux 發(fā)行版上切換到淘寶的 npm 鏡像源,需要的朋友可以參考下2025-03-03