8000 Work queues tutorial · lengocgiang/rabbitmq-tutorials@8961f92 · GitHub
[go: up one dir, main page]

Skip to content

Commit 8961f92

Browse files
committed
Work queues tutorial
1 parent b282cde commit 8961f92

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

javascript-nodejs/src/new_task.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#!/usr/bin/env node
2+
3+
var amqp = require('amqplib');
4+
var when = require('when');
5+
6+
var conn = amqp.connect('amqp://localhost');
7+
conn.then(createChannel).then(null, console.warn);
8+
9+
function createChannel(conn) {
10+
return when(
11+
conn.createChannel().
12+
then(sendMessage)).
13+
ensure(function() {
14+
conn.close();
15+
});
16+
}
17+
18+
function sendMessage(ch) {
19+
var q = 'task_queue';
20+
var ok = ch.assertQueue(q, {durable: true});
21+
22+
return ok.then(function(_ignore) {
23+
var msg = process.argv.slice(2).join(' ') || "Hello World!";
24+
ch.sendToQueue(q, new Buffer(msg), {persistent: true});
25+
console.log(" [x] Sent '%s'", msg);
26+
return ch.close();
27+
});
28+
}

javascript-nodejs/src/worker.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#!/usr/bin/env node
2+
3+
var amqp = require('amqplib');
4+
5+
var conn = amqp.connect('amqp://localhost');
6+
conn.then(createChannel).then(null, console.warn);
7+
8+
function createChannel(conn) {
9+
process.once('SIGINT', function() { conn.close(); });
10+
return conn.createChannel().then(consume);
11+
}
12+
13+
function consume(ch) {
14+
var ok = ch.assertQueue('task_queue', {durable: true});
15+
16+
ok = ok.then(function() { ch.prefetch(1); });
17+
ok = ok.then(function(_ignore) {
18+
return ch.consume(
19+
'task_queue',
20+
function doSomeWork(msg) {
21+
console.log(" [x] Received '%s'", msg.content.toString());
22+
var secs = msg.content.toString().split('.').length - 1;
23+
setTimeout(function() {
24+
console.log(" [x] Done");
25+
ch.ack(msg);
26+
}, secs * 1000);
27+
},
28+
{noAck: false});
29+
});
30+
31+
return ok.then(function(_consumeOk) {
32+
console.log(' [*] Waiting for messages. To exit press CTRL+C');
33+
});
34+
}

0 commit comments

Comments
 (0)
0