Last active
August 29, 2015 14:00
-
-
Save riston/11052692 to your computer and use it in GitHub Desktop.
RabbitMQ nodejs example message ack
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
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); | |
}); | |
}); |
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
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