简体   繁体   中英

Node.js AMQP fanout

I'm trying to build a distributed system, I am using postwait/node-amqp . Being new to this I find the docs to be very unhelpful.

Now a diagram on my plan:

Client -> Gate -> Q -> EatProcessor
                    -> WalkProcessor
                    -> Logger

Let us say the client sent Start Eating . The Gate receives it and adds it to the Q the message being about eating only the EatProcessor should get the message from the Q .

So let us say EatProcessor:

connection.queue('Q', {autoDelete: false}, function(queue){
        queue.subscribe(function(msg){
            // recv message
        });
    });

So how do I:

  • Let the Eat Processor only get the eat stuff from the Q
  • Let the Walk Processor only get the walk stuff from the Q
  • And the Logger will get everything from the Q and just log.

I was reading around and maybe the gate should be a fanout? But I dont see in the docs how to do a fanout.

If a fanout does it mean everyone will get the message? Let us say I didn't write the logger yet, I'll write it in the feature but when I write it I would like to just listen directly to the Q and not change any code on the Gate .

OK, so first of all use exchanges. That way you'll be able to publish to more then one queue at the same time. I don't know RabbitMQ with Node.js but I think something like that should work:

// define a queue for each type
connection.queue('eat-q', {autoDelete: false}, function(eat_queue) {
    // ...
    connection.queue('walk-q', {autoDelete: false}, function(eat_queue) {
        // ...
        connection.queue('log-q', {autoDelete: false}, function(log_queue) {
            // ...
        });
    });
});

Then define the exchange and do the binding:

connection.exchange('my-exchange', function(exchange) {
    eat_queue.bind('my-exchange', 'eat', function() {
        // ...
    });
    walk_queue.bind('my-exchange', 'walk', function() {
        // ...
    });
    log_queue.bind('my-exchange', 'walk', function() {
        // ...
    });
    log_queue.bind('my-exchange', 'eat', function() {
        // ...
    });
});

Finally you can publish to the exchange:

exchange.publish('eat', 'my message', {}, function() {
    // ...
});

The message should end up in both eat-q and log-q .

Note that you should use some kind of flow library here like caolan's async.js or kriskowal's q cause you'll end up with lots of callbacks. I prefer the second one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM