Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- The example consists of 3 files:
- queue.js => implements the plugin
- bar.js => implements a basic service
- foo.js => implements another service which calls bar.js
- You will need redis running on localhost port 6379, or change the configurations
- */
- //**************** queue.js
- // Fire and forget rpc for Studio.
- var localServices ={};
- //Using redis as message broker for simplicity
- var Redis = require('ioredis');
- // Adding a prefix to avoid conflict with other lists on redis
- var QUEUE_PREFIX = 'studio_queue_';
- /*
- Each service will have their own queue, and will wait for messages
- You can implement any message broker you want,
- doing a naive redis implementation just to keep really simple
- */
- module.exports = function(options,Studio){
- "use strict";
- var redisSender = new Redis();
- var sendMessageToQueue = Studio.promise.promisify(redisSender.lpush).bind(redisSender);
- options.onStart(function(serv,ref){
- var redisClient = new Redis();
- localServices[serv.id] = redisClient;
- /*
- When you start a new service, makes it listen for a message on his queue, when a message arrives,
- parse and call the service
- */
- redisClient.blpop(QUEUE_PREFIX+serv.id,0,function(error,message){
- message = JSON.parse(message[1]);
- message = Object.keys(message).map(function(key){
- return message[key];
- });
- /*
- Here we call the service, we shouldnt use serv.fn, because this would bypass the
- interceptSend of other plugins, so we use ref (which is basically the same thing as Studio(serv.id))
- */
- ref.apply(serv,message);
- });
- });
- options.onStop(function(serv,ref){
- /*
- Remove from localServices and disconnect
- */
- if(localServices[serv.id]){
- localServices[serv.id].disconnect();
- localServices[serv.id] = null;
- }
- });
- options.interceptSend(function(send,receiver){
- // Whenever a service is called, if is local call the local service, if not send message to a queue
- return function(){
- if(localServices[receiver]){
- return send.apply(null,arguments);
- }else{
- return sendMessageToQueue(QUEUE_PREFIX+receiver,JSON.stringify(arguments));
- }
- }
- });
- };
- //**************** foo.js
- var Studio = require('studio');
- var StudioQueue = require('./queue');
- Studio.use(StudioQueue);
- Studio(function foo() {
- return Studio('bar')({hello:'Hello World!!!'});
- });
- Studio('foo')();
- //**************** bar.js
- var Studio = require('studio');
- var StudioQueue = require('./queue');
- Studio.use(StudioQueue);
- Studio(function bar(message) {
- console.log(message);
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement