amqp.connect(host) .then(connection => connection.createConfirmChannel()) .then((channel) => { channels[host] = channel[host] ? channels[host] : {}; channels[host][context] = channel; return channels[host][context]; }) .catch((error) => { helpers.log('error', error.message, options); return error; })
async function init() { const conn = await amqp.connect('amqp://localhost'); process.once('SIGINT', conn.close.bind(conn)); ch = await conn.createConfirmChannel(); logger.info('client has connected to mq'); await ch.assertQueue(queueName, { durable: false }); }
const listen = async () => { // connect to RabbitMQ let connection = await amqp.connect(messageQueueConnection) // create a channel and prefetch one message at a time let channel = await connection.createChannel() await channel.prefetch(1) // create a second channel to send back the results let resultsChannel = await connection.createConfirmChannel() // start consuming message await consume({ connection, channel, resultsChannel }) }
// handle the request app.post('/api/v1/process', async (req, res) => { // save request id and increment let request_id = last_request_id last_request_id++ // connect to RabbitMQ and create a channel let connection = await amqp.connect(messageQueueConnection) let channel = await connection.createConfirmChannel() // publish the data to RabbitMQ let request_data = req.body.data console.log(`Published a request message, request id: ${request_id}`) await publishToChannel(channel, { routingKey: "request", exchangeName: "processing", data: { request_id, request_data } }) // send the request id in the response res.send({ request_id }) })
// --- /** * @summary Creates a confirm channel * or returns an existing one from cache * @returns {undefined} Nothing */ async function createChannel() { try { if (channel !== null) return channel; const connection = await amqp.connect(uri()); // NOTE: In production, connection event handlers // should be attached here. See API Reference for // a complete list of emitted events. channel = await connection.createConfirmChannel(); // NOTE: In production, channel event handlers // should be attached here. See API Reference for // a complete list of emitted events. } catch (e) { return e; } }