LoginSignup
6
6

More than 5 years have passed since last update.

node-amqpでRabbitMQに接続してみる

Posted at

環境・バージョン
Windows 7
Node.js 0.12.4
RabbitMQ 3.4.1
node-amqp 0.2.4

Subscriber

sub.js
var amqp = require('amqp');

var options = {
    host: 'localhost',
    port: 5672,
};

var connection = amqp.createConnection(options);

connection.on('error', function(e) {
    throw e;
});

connection.on('close', function(e) {
    console.log('connection closed.');
});

connection.on('ready', function() {
    console.log('connected to ' + connection.serverProperties.product);

    connection.queue('my-queue', function(q) {
        q.bind('#');
        q.subscribe(function(message) {
            console.log(message.data.toString());
        });
    });
});

Publisher

pub.js
var amqp = require('amqp');

var options = {
    host: 'localhost',
    port: 5672,
};

var connection = amqp.createConnection(options);

connection.on('error', function(e) {
    throw e;
});

connection.on('close', function(e) {
    console.log('connection closed.');
});

connection.on('ready', function() {
    console.log('connected to ' + connection.serverProperties.product);

    sendMessage(connection, 'my-queue', 'Hello, AMQP1!!');
    sendMessage(connection, 'my-queue', 'Hello, AMQP2!!');
    sendMessage(connection, 'my-queue', 'Hello, AMQP3!!');
});

function sendMessage(connection, queue_name, payload) {
    connection.publish(queue_name, payload);
}

実行結果

connected to RabbitMQ
Hello, AMQP1!!
Hello, AMQP2!!
Hello, AMQP3!!
6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6