Pregunta

I'm writing a nodejs based rest API.

My API have different methods like put /friends that adds a user to friend list of the currently logged in user.

I want to notify the other user, that he has been added as a friend, via different methods (push notification, mail, whatever). I dont want to do the notification inside the API process, instead I want to publish an events that another nodejs process (might be even running on a different machine), will pickup and do the notification work.

What are the accepted methods to implement such architecture? The key here is that I want pub/sub pattern between different nodejs processes that might not even share the same machine, so I guess regular EventEmitter wont help there.

Thanks for help!

¿Fue útil?

Solución

  1. The first thing that came to mind was to use @substack's dnode project. He wrote a blog post a few years ago about adapting dnode, which is a JavaScript-based RPC framework, into a PubSub framework. Details here: http://substack.net/roll_your_own_pubsub_with_dnode

  2. It seems like Faye is also becoming popular, where you can spin up a node.js server which acts as a message manager.

  3. Additionally you may look at using socket.io and redis as described here.

You could also try eliminating infrastructure overhead by using an external real-time network like PubNub. PubNub is free for up to 20 daily devices (see the pricing page.) They have some examples on the node.js API GitHub page, but the basic structure is:

var pubnub = require("pubnub").init({
    publish_key   : "demo",
    subscribe_key : "demo"
});

pubnub.subscribe({
    channel  : "my_channel",
    callback : function(message) {
        console.log( "Friend request notice: ", message );
    }
});

To send messages, you can use the similar publish.

pubnub.publish({
    channel : "my_channel",
    message : 'You are now friends with Bob.'
});

This is obviously much simpler to get working and could help validate the Pub/Sub model you're choosing for your (potentially) multiple servers. Good luck!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top