Master-slave solution for single-point service based on redis
Install it via npm:
npm install node-master-slave
And include in your project:
import MasterSlaveClient from 'node-master-slave';
const client = new MasterSlaveClient(redis); // ioredis client
client.on("change", function(c) {
console.log('isMaster: ', c.isMaster());
console.log('isAlive: ', c.isAlive());
if (c.isMaster()) {
setTimeout(function() {
c.broadcastMessage('test message');
c.changeToSlave();
}, Math.random() * 3000 + 2000)
}
});
client.on("message", function(message) {
console.log(message);
})
client.connect();
new Client(redisConnection, {beatInterval = 250, expire = 4, channel = 'REDIS_MASTER_SLAVE'}): client
构造函数
redisConnection: redis 连接, 推荐使用 ioredis
beatInterval: 心跳检测最大频率 (单位 ms)
expire: 心跳过期时间 (单位 s)
channel: master slave 集合标识
是否是 master
是否是 slave
创建客户端连接
断开客户端连接
master 切换为 slave
客户端 id
客户端是否已连接
master slave 集合广播消息
监听 change
事件, 当 master 和 slave 状态切换时触发回调
监听 message
事件, 收到 broadcastMessage
广播的消息后触发
MIT