我正在尝试使用sub / pub redis.io-redis
适配器扩展聊天应用程序,但是在群集模式下不能很好地工作,我不确定我做错了什么。这是我的服务器代码:
这是我的server.js文件,它将成为集群模式并初始化express
const cluster = require('cluster');
const os = require('os');
if (cluster.isMaster) {
for (let index = 0; index < os.cpus().length; index++) {
cluster.fork();
}
} else {
const express = require('express');
const app = express();
const chatCat = require('./app');
app.use(chatCat.session);
app.use(passport.initialize());
app.use(passport.session());
app.use('/', chatCat.router);
chatCat.ioServer(app).listen(app.get('port'), () => {
console.log('chatCAT Running on Port:', app.get('port'));
});
}
这是app \ index.js
const redis = require('redis').createClient;
const adapter = require('socket.io-redis');
let ioServer = app => {
const server = require('http').Server(app);
const io = require('socket.io')(server);
io.serveClient('transports', ['websocket']);
let pubClient = redis(config.redis.port, config.redis.host, {
auth_pass: config.redis.password
});
let subClient = redis(config.redis.port, config.redis.host, {
auth_pass: config.redis.password,
return_buffers: true
});
io.adapter(
adapter({
pubClient,
subClient
})
);
io.use((socket, next) => {
require('./session')(socket.request, {}, next);
});
require('./socket')(io, app);
return server;
}
这是socket / index.js
module.exports = (io, app) => {
let allrooms = app.locals.chatrooms;
io.of('/roomslist').on('connection', socket => {
socket.on('getChatrooms', () => {
console.log('allrooms', allrooms);
socket.emit('chatRoomsList', JSON.stringify(allrooms));
});
socket.on('createNewRoom', newRoomInput => {
if (!h.findRoomByName(allrooms, newRoomInput)) {
allrooms.push({
room: newRoomInput,
roomID: h.randomHex(),
users: []
});
socket.emit('chatRoomsList', JSON.stringify(allrooms));
socket.broadcast.emit('chatRoomsList', JSON.stringify(allrooms));
}
});
});
}
allrooms
是列表室,在我的应用程序中,当用户登录时,用户将看到房间列表,但是有时他们看到它,有时却看不到,我调试并看到变量allrooms为空。我研究了一些教程,示例仅将redis适配器io.adapter(adapter({pubClient,subClient}));
连接到套接字。
我想知道套接字是否会自动处理它本身,还是必须手动使用pub / sub。因此,如果我必须手动发布/订阅,能否举个例子