Created
October 8, 2018 19:56
-
-
Save kenanhancer/ab61a51db3661bacb9d73cfd43a99ddf to your computer and use it in GitHub Desktop.
Node.js Handling long-running requests with RabbitMQ
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
| var amqp = require('amqplib/callback_api'); | |
| var request = require('request'); | |
| request.post('http://localhost:3000/messages', function (error, response, body) { | |
| console.log(response.body); | |
| // Connect to the server and wait for the queue | |
| amqp.connect('amqp://192.168.33.19', (err, conn) => { | |
| conn.createChannel((err, ch) => { | |
| const q = 'person_queue'; | |
| ch.assertQueue(q, { | |
| durable: false | |
| }); | |
| console.log(` [*] Waiting for messages in ${q}. To exit press CTRL+C`); | |
| ch.consume(q, msg => { | |
| console.log(` [x] Received ${msg.content}`); | |
| conn.close(); | |
| }, { | |
| noAck: true | |
| }); | |
| }); | |
| }); | |
| }); |
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 express = require('express'); | |
| const app = express(); | |
| const amqp = require('amqplib/callback_api'); | |
| app.route('/messages').post((req, res) => { | |
| amqp.connect('amqp://192.168.33.19', (err, conn) => { | |
| conn.createChannel((err, ch) => { | |
| const q = 'person_queue'; | |
| ch.assertQueue(q, { durable: false }); | |
| setTimeout(() => { | |
| const person = { personId: 1, FirstName: 'Kenan', LastName: 'Hancer' }; | |
| const msg = JSON.stringify(person); | |
| ch.sendToQueue(q, Buffer.from(msg)); | |
| console.log(` [X] Send ${msg}`); | |
| }, 6000); | |
| }); | |
| // The connection will close in 10 seconds | |
| setTimeout(() => { | |
| conn.close(); | |
| }, 10000); | |
| }); | |
| res.send('The POST request is being processed!'); | |
| }); | |
| const server = app.listen(3000, function () { | |
| const address = server.address(); | |
| const host = address.address; | |
| const port = address.port; | |
| console.log(`Nodejs with RabbitMQ app listening at http://${host}:${port}`); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment