Skip to content

Node.js based forum software built for the modern web

Allow single-host clusters to not send pubsub and socket.io messages through the database. (#6659)

Ben Lubarc1e98eefa7fe
diff --git a/install/package.json b/install/package.json
index 94ab028d33..e09864dc4d 100644
--- a/install/package.json
+++ b/install/package.json
@@ -95,6 +95,7 @@
"serve-favicon": "^2.4.5",
"sitemap": "^1.13.0",
"socket.io": "2.1.1",
+ "socket.io-adapter-cluster": "^1.0.1",
"socket.io-adapter-mongo": "^2.0.1",
"socket.io-client": "2.1.1",
"socket.io-redis": "5.2.0",
diff --git a/loader.js b/loader.js
index 3071a6f8d5..9150c868c8 100644
--- a/loader.js
+++ b/loader.js
@@ -36,6 +36,10 @@ Loader.init = function (callback) {
};
}
+ if (nconf.get('singleHostCluster')) {
+ require('socket.io-adapter-cluster/master')();
+ }
+
process.on('SIGHUP', Loader.restart);
process.on('SIGUSR2', Loader.reload);
process.on('SIGTERM', Loader.stop);
@@ -88,6 +92,11 @@ Loader.addWorkerEvents = function (worker) {
console.log('[cluster] Reloading...');
Loader.reload();
break;
+ case 'pubsub':
+ workers.forEach(function (w) {
+ w.send(message);
+ });
+ break;
}
}
});
diff --git a/src/pubsub.js b/src/pubsub.js
index 6b6f12d171..82c4a1b57b 100644
--- a/src/pubsub.js
+++ b/src/pubsub.js
@@ -1,5 +1,6 @@
'use strict';
+var EventEmitter = require('events');
var nconf = require('nconf');
var real;
@@ -12,9 +13,22 @@ function get() {
var pubsub;
if (nconf.get('isCluster') === 'false') {
- var EventEmitter = require('events');
pubsub = new EventEmitter();
pubsub.publish = pubsub.emit.bind(pubsub);
+ } else if (nconf.get('singleHostCluster')) {
+ pubsub = new EventEmitter();
+ pubsub.publish = function (event, data) {
+ process.send({
+ action: 'pubsub',
+ event: event,
+ data: data,
+ });
+ };
+ process.on('message', function (message) {
+ if (message && typeof message === 'object' && message.action === 'pubsub') {
+ pubsub.emit(message.event, message.data);
+ }
+ });
} else if (nconf.get('redis')) {
pubsub = require('./database/redis/pubsub');
} else if (nconf.get('mongo')) {
diff --git a/src/socket.io/index.js b/src/socket.io/index.js
index 884a7e432c..bf7d7cdd7d 100644
--- a/src/socket.io/index.js
+++ b/src/socket.io/index.js
@@ -27,7 +27,13 @@ Sockets.init = function (server) {
path: nconf.get('relative_path') + '/socket.io',
});
- io.adapter(nconf.get('redis') ? require('../database/redis').socketAdapter() : db.socketAdapter());
+ if (nconf.get('singleHostCluster')) {
+ io.adapter(require('socket.io-adapter-cluster')());
+ } else if (nconf.get('redis')) {
+ io.adapter(require('../database/redis').socketAdapter());
+ } else {
+ io.adapter(db.socketAdapter());
+ }
io.use(socketioWildcard);
io.use(authorize);