Last active
December 9, 2022 03:40
-
-
Save daliborgogic/37bcf51756cbd60190519c5c4394311e to your computer and use it in GitHub Desktop.
amqp async/await node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const amqp = require('amqplib') | |
const eventEmitter = require('events') | |
class OopsEmitter extends eventEmitter {} | |
const oopsEmitter = new OopsEmitter() | |
;(async () => { | |
try { | |
const conn = await amqp.connect('amqp://localhost?heartbeat=5s') | |
const ch = await conn.createChannel() | |
const queueName = 'oops.*' | |
const msg = 'ping ' + new Date | |
await ch.assertQueue(queueName, { durable: false }) | |
// Publish | |
await ch.sendToQueue(queueName, Buffer.from(msg, 'utf8')) | |
console.log('[x] Sent %s', msg) | |
// Subscribe | |
await ch.consume(queueName, msg => { | |
if (msg !== null) { | |
oopsEmitter.emit('event', msg.content.toString()) | |
ch.ack(msg) | |
} | |
}) | |
await ch.close() | |
await conn.close() | |
} catch (error) { | |
console.error(error) | |
} | |
})() | |
oopsEmitter.on('event', x => { | |
console.log('A ', process.hrtime.bigint()) | |
function cb () { | |
console.log('B ' , process.hrtime.bigint()) | |
} | |
process.nextTick(cb) | |
setImmediate(() => console.log('C ', process.hrtime.bigint())) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment