Created
July 19, 2012 12:13
-
-
Save mnrtks/3143433 to your computer and use it in GitHub Desktop.
[RabbitMQ]1つのQueueに複数のルーティングキーを結びつけるサンプルコード
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'); | |
var util = require('util'); | |
/* | |
* 指定したルーティングキーで定期的にデータを送信する | |
* Usage: node pub.js key1 key2 key3 | |
*/ | |
function main(argv) { | |
var seq = 0; | |
// Create amqp connection | |
var connection = amqp.createConnection({ | |
host: 'localhost', | |
port: 5672 | |
}, { | |
// amq.directはルーティングキーが完全に一致したときのみ | |
// amq.topicはルーティングキーにワイルドカードを使用出来る | |
defaultExchangeName: "amq.direct" | |
}); | |
connection.on('ready', function () { | |
console.log('Pub: Connection ready'); | |
// 定期的にPublishする | |
setInterval(function () { | |
var index = parseInt(Math.random() * argv.length); | |
var channel = argv[index]; | |
var request = { | |
channel: channel, | |
data: seq++ | |
}; | |
connection.publish(channel, JSON.stringify(request)); | |
util.log(channel); | |
}, 1000); | |
}); | |
} | |
var channels = process.argv.slice(2); | |
main(channels); |
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'); | |
var util = require('util'); | |
/* | |
* 1つのQueueで複数のルーティングキーを待ち受ける | |
* Usage: node sub.js queueName key1 key2 | |
*/ | |
function main(argv) { | |
var connection = amqp.createConnection({ | |
host: 'localhost', | |
port: 5672 | |
}, { | |
// amq.directはルーティングキーが完全に一致したときのみ | |
// amq.topicはルーティングキーにワイルドカードを使用出来る | |
defaultExchangeName: "amq.direct" | |
}); | |
// Create amqp connection | |
connection.on('ready', function () { | |
console.log('Sub: Connection ready'); | |
// Create queue | |
connection.queue(argv[0], function (queue) { | |
util.log("Queue " + queue.name + " is opened"); | |
for (var i = 1; i < argv.length; i++) { | |
// bind routing key | |
queue.bind("amq.direct", argv[i]); | |
} | |
queue.subscribe(function (message) { | |
var request = JSON.parse(message.data.toString('utf8')); | |
util.log("Channel: " + request.channel + " , Data: " + request.data); | |
}); | |
}); | |
}); | |
}; | |
var channels = process.argv.slice(2); | |
main(channels); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment