Skip to content

Instantly share code, notes, and snippets.

@riston
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save riston/11052692 to your computer and use it in GitHub Desktop.
Save riston/11052692 to your computer and use it in GitHub Desktop.
RabbitMQ nodejs example message ack
var amqp = require('amqp'),
C = require('config'),
config = C.server,
connection;
connection = amqp.createConnection({
url: config.rabbitmq.url
});
connection.on('ready', function() {
console.log('Ready');
connection.queue('task_queue', {
autoDelete: false,
durable: true
}, function(queue) {
console.log('Task queue');
function queue(i) {
var message = 'base_message' + ' ' + i;
connection.publish('task_queue', message, {
deliveryMode: 2
});
console.log(" [x] Sent %s", message);
if (i < 30) {
setTimeout(function() {
queue(i + 1);
}, 700);
}
}
queue(1);
});
});
var amqp = require('amqp'),
C = require('config'),
config = C.server,
connection;
connection = amqp.createConnection({
url: config.rabbitmq.url,
clientProperties: {
capabilities: {
consumer_cancel_notify: false
}
}
});
function main(workerID) {
var workerStr = workerID ? "W[" + workerID + "]" : "";
connection.on('ready', function() {
connection.queue('task_queue', {
autoDelete: false,
durable: true
}, function(queue) {
console.log('[*] Waiting for messages. To exit press CTRL+C');
queue.subscribe({
ack: true,
prefetchCount: 1
}, function(json, headers, info, message) {
var body = json.data.toString('utf-8');
console.log(" [*]%s Received %s", workerStr, body);
setTimeout(function() {
var rnd = Math.floor((Math.random() * 3) + 1);
if (rnd == 2) {
console.log(" [x]%s Failed %s", workerStr, body);
message.reject(true);
//queue.shift(true, true); // NOT WORK: https://github.com/postwait/node-amqp/issues/210
} else {
console.log(" [√]%s Done %s", workerStr, body);
queue.shift(); // basic_ack equivalent
}
}, 4000);
});
});
});
}
main(2321321);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment