JSON object sharing between different clusters

5

Good afternoon, I would like to know how do I share a JSON object between different clusters. I currently have 3 clusters listening to three different ports. It is necessary to have an object saved in memory so that the three clusters can access the information of this object.

var express = require('express');
var net = require('net');
var Files = require('./lib/Files');

var app = express();
var port = 9000;

if(!myObject) {
    // Cria o objeto na memória para que os outros sockets possam acessar
}

// Cria o Servidor
net.createServer(function (socket) {
    if (config.STRLOG) {
        console.log("Dispositivo Conectado: " + socket.remoteAddress + ":" + socket.remotePort);
    }

    socket.on('data', function (data) {
        console.log(data);
    });

    socket.on('error', function (err) {
        console.log('> SOCKET ERROR');
        Files.SocketErrorLog(port, err);
        console.log('------------------');
    });
}).listen(port);

module.exports = app;
    
asked by anonymous 01.12.2016 / 17:15

1 answer

2

You can use the REDIS database to save your json and your clusters can access the objects from there eg:

var express = require('express'),
redis = require('redis'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
redisStore = require('connect-redis')(session),
logger = require('morgan'),
bodyParser = require('body-parser');


var client = redis.createClient(),//CREATE REDIS CLIENT
    app = express();

app.use(cookieParser('strongsecretcode'));
app.use(session(
    {
        secret: 'strongsecretcodehere', 
        store: new redisStore({ host: 'localhost', port: 6379, client: client }),
        saveUninitialized: false, // don't create session until something stored,
        resave: false // don't save session if unmodified
    }
));

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

var router = express.Router();

router.get('/yoursession/set/:value', function(req, res) {
    req.session.user = req.params.value;
    res.send('session saved in Redis');
});

app.get('/yoursession/get/', function(req, res) {
    if(req.session.user)
        res.send(req.session.user);
    else
        res.send("no session value stored in Redis ");
});

app.use('/', router);
var server = app.listen(2001, function() {
    console.log('REDIS SESSION server is listening on port %d', server.address().port);
});

In the book: Web applications real-time with Node.js Page 29 explains how to use redis in cluster-based applications.

    
09.12.2016 / 21:23