A simple way to wrap a single-instance module to enable it to work with node cluster.
Go to file
AJ ONeal 4ad7b03117 v1.0.7 2018-04-20 19:14:15 -06:00
process v1.0.6 2018-04-20 19:13:48 -06:00
.gitignore Initial commit 2016-09-08 16:09:31 -06:00
LICENSE Initial commit 2016-09-08 16:09:31 -06:00
README.md add forks on 'fork' event 2016-09-08 18:25:08 -06:00
index.js v1.0.0 2016-09-08 16:23:40 -06:00
master.js v1.0.6 2018-04-20 19:13:48 -06:00
package.json v1.0.7 2018-04-20 19:14:15 -06:00
prefixes.js v1.0.6 2018-04-20 19:13:48 -06:00
test.js v1.0.6 2018-04-20 19:13:48 -06:00
worker.js v1.0.6 2018-04-20 19:13:48 -06:00

README.md

cluster-rpc

A simple way to wrap node.js modules for use with cluster even though they were designed to be used in a single non-cluster instance.

Install

npm install --save cluster-rpc

Usage

In the master process you will create the real instance of whatever module you're trying to use (for example express-session/session/memory, sqlite3, level) and then you will supply the names of the methods you wish to export to worker processes.

By default each worker will be added when cluster emits a fork event. If needed you can set addOnFork to false and call addWorker(worker) manually.

master

// You can pick any module with thunk-style callbacks
// For example:
var db = require('level')('./mydb')


// Wrap the instance
var crpc = require('cluster-rpc/master').create({
  addOnFork: true                 // default
, instance: db
, methods: [ 'get', 'put' ]
, name: 'foo-level'
});


// If you set addOnFork to false, You must manually add each worker
// crpc.addWorker(cluster.fork());


crpc.then(function (db) {
  // processes are connected and ready
  // 'db' is the original instance
});

worker

// retrieve the instance
var crpc = require('cluster-rpc/worker').create({
  name: 'foo-level'
});


// all listed methods will be rpc'd
crpc.then(function (db) {
  // db.put, db.get
});

Example

'use strict';

var cluster = require('cluster');
var crpc;


if (cluster.isMaster) {


  crpc = require('cluster-rpc/master').create({
    addOnFork: false
  , instance: require('level')('./mydb')
  , methods: [ 'get', 'put' ]
  , name: 'foo-level'
  });
  crpc.addWorker(cluster.fork());
  crpc.then(function () {
    db.put('foo', 'bar');
  });


}
else {


  crpc = require('cluster-rpc/worker').create({
    name: 'foo-level'
  });


}


crpc.then(function (db) {
  setTimeout(function () {
    db.get('foo', function (err, result) {
      console.log("db.get('foo')", result);
    });
  }, 250);
});