開發與維運

nodejs AMQP服務端訂閱的實現

步驟 :  

1)環境安裝 node.js (下載安裝包,下一步.....就行了)

這個是我的版本

IT-C1MPD4X5G943:webpack11 ganjun$ node -v

v14.15.1

IT-C1MPD4X5G943:webpack11 ganjun$

2)安裝nodejs的包管理器 cnpm

這個是我的版本

IT-C1MPD4X5G943:webpack11 ganjun$ cnpm -v

[email protected] (/usr/local/lib/node_modules/cnpm/lib/parse_argv.js)

[email protected] (/usr/local/lib/node_modules/cnpm/node_modules/npm/lib/npm.js)

[email protected] (/usr/local/bin/node)

[email protected] (/usr/local/lib/node_modules/cnpm/node_modules/npminstall/lib/index.js)

prefix=/usr/local

darwin x64 20.2.0

registry=https://r.npm.taobao.org

3)參考官網代碼

https://help.aliyun.com/document_detail/143599.html?spm=a2c4g.11186623.6.656.5dd67cd8K9IMzE

4)代碼以及依賴

在package.json中添加以下依賴。

"dependencies": {
    "rhea": "^1.0.12"
 }

代碼

constcontainer=require('rhea');
constcrypto=require('crypto');
//創建Connection。
varconnection=container.connect({
//接入域名,請參見AMQP客戶端接入說明文檔。
'host':'11112560*******.iot-amqp.cn-shanghai.aliyuncs.com',
'port':5671,
'transport':'tls',
'reconnect':true,
'idle_time_out':60000,
//userName組裝方法,請參見AMQP客戶端接入說明文檔。其中的iotInstanceId,企業版實例請填寫實例ID,公共實例直接刪除${YourIotInstanceId}。
'username':'4444444444|authMode=aksign,signMethod=hmacsha1,timestamp=1573489088171,authId=LTAIVne33sFywOG8,iotInstanceId=,consumerGroupId=DEFAULT_GROUP|', 
//計算簽名,password組裝方法,請參見AMQP客戶端接入說明文檔。
'password':hmacSha1('9ViU8**********', 'authId=LTAIVne33sFywOG8&timestamp=1573489088171'),
});
//創建Receiver Link。
varreceiver=connection.open_receiver();
//接收雲端推送消息的回調函數。
container.on('message', function(context) {
varmsg=context.message;
varmessageId=msg.message_id;
vartopic=msg.application_properties.topic;
varcontent=Buffer.from(msg.body.content).toString();
// 輸出內容。
console.log(content);
//發送ACK,注意不要在回調函數有耗時邏輯。
context.delivery.accept();
});
//計算password簽名。
functionhmacSha1(key, context) {
returnBuffer.from(crypto.createHmac('sha1', key).update(context).digest())
.toString('base64');
}

One Comment

  • anna lily

    Interesting topic for a blog. I have been searching the Internet for fun and came upon your website. Fabulous post. Thanks a ton for sharing your knowledge! It is great to see that some people still put in an effort into managing their websites. I’ll be sure to check back again real soon.

Leave a Reply to anna lily Cancel reply

Your email address will not be published. Required fields are marked *