Created
October 2, 2015 03:40
-
-
Save diegodfsd/33b8efc699ff86206181 to your computer and use it in GitHub Desktop.
This file contains 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
/* | |
* This code requires both RabbitMQ and delayed message plugin is installed. | |
* The plugin can be found here https://github.com/rabbitmq/rabbitmq-delayed-message-exchange/ | |
* | |
* Refeence: https://www.rabbitmq.com/blog/2015/04/16/scheduling-messages-with-rabbitmq/ | |
*/ | |
'use strict'; | |
var amqp = require('amqplib'), | |
connection = amqp.connect('amqp://localhost'), | |
queue = 'my-messages', | |
exchange = 'my-exchange'; | |
connection.then(function (conn) { | |
return conn.createChannel() | |
.then(function (ch) { | |
// Creates a queue | |
ch.assertQueue(queue).then(function () { | |
// Creates an exchange | |
ch.assertExchange(exchange, 'x-delayed-message', { arguments: { 'x-delayed-type': 'direct' } }).then(function () { | |
// Creates a bind between queue and exchange | |
ch.bindQueue(queue, exchange).then(function () { | |
// Send messages with delay | |
ch.publish(exchange, '', new Buffer('3. my delayed message'), { persistent: true, headers: { 'x-delay': 10000 } }); | |
ch.publish(exchange, '', new Buffer('1. my delayed message'), { persistent: true, headers: { 'x-delay': 3000 } }); | |
ch.publish(exchange, '', new Buffer('4. my delayed message'), { persistent: true, headers: { 'x-delay': 12000 } }); | |
ch.publish(exchange, '', new Buffer('2. my delayed message'), { persistent: true, headers: { 'x-delay': 5000 } }); | |
console.log('messages sent!'); | |
}); | |
}); | |
}); | |
}); | |
}); | |
connection.then(function (conn) { | |
return conn.createChannel() | |
.then(function (ch) { | |
ch.consume(queue, function (msg) { | |
if (msg !== null) { | |
console.log(msg.content.toString()); | |
ch.ack(msg); | |
} | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment