cluster-rpc.js/README.md

110 lines
1.8 KiB
Markdown
Raw Normal View History

2016-09-08 22:23:40 +00:00
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.
You must pass each worker via `addWorker()` so that it signals the worker to creates
its own rpc-wrapped instance.
### master
```javascript
// 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({
instance: db
, methods: [ 'get', 'put' ]
, name: 'foo-level'
});
// You must add each worker
crpc.addWorker(cluster.fork());
crpc.then(function (db) {
// processes are connected and ready
// 'db' is the original instance
});
```
### worker
```javascript
// 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
=======
```javascript
'use strict';
var cluster = require('cluster');
var crpc;
if (cluster.isMaster) {
crpc = require('cluster-rpc/master').create({
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);
});
```