1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| class RabbitMQ { constructor(opts) { this.opts = Object.assign({ "protocol": "amqp", "hostname": "localhost", "port": 5672, "username": "guest", "password": "guest" }, opts); this.trynum = 0; this.maxtrynum = 9; }
async sendQueueMsg(queueName, msg, resultCallback, retry) { if (!retry) { this.trynum = 0; } const amqp = require('amqplib'); let channel = null; let conn = null; let self = this;
function retryAction() { setTimeout(() => { try { if (channel) { channel.close(); if (conn) { conn.close(); } } } catch (e) { console.info("关闭失败") } }, 1000);
if (self.trynum < self.maxtrynum) { self.trynum += 1; console.info("MQ失败尝试", "第" + self.trynum + "次", msg) setTimeout(() => { self.sendQueueMsg(queueName, msg, resultCallback, true); }, 10000) } else { resultCallback && resultCallback("Fail: " + msg); } }
try { let msgBuffer = Buffer.from(msg, "utf8"); conn = await amqp.connect(this.opts); conn.on('error', function (err) { console.info("conn error") }); channel = await conn.createChannel(); await channel.assertQueue(queueName); let data = await channel.sendToQueue(queueName, msgBuffer, { persistent: true }); if (data) { resultCallback && resultCallback("Success: " + msg); setTimeout(() => { try { if (channel) { channel.close(); if (conn) { conn.close(); } } } catch (e) { console.info("关闭失败") } }, 1000); } else { retryAction(); } } catch (e) { retryAction(); } } }
exports.RabbitMQ = RabbitMQ;
|