/*redis逻辑处理*/
const Redis = require('ioredis');
const requestConfig = require('../config/redis_config');
const request = require('../utils/request').post;
// 普通模式
// const options = {
// host: requestConfig.redisHost, // Redis host
// port: requestConfig.redisPort1, // Redis port
// }
// 哨兵模式,多端口
const options = {
sentinels: [
{
host: requestConfig.redisHost, // Redis host
port: requestConfig.redisPort1, // Redis port
},
{
host: requestConfig.redisHost, // Redis host
port: requestConfig.redisPort2, // Redis port
},
{
host: requestConfig.redisHost, // Redis host
port: requestConfig.redisPort3, // Redis port
}
],
name: 'mymaster',
password: requestConfig.redisPwd,
};
const redis = new Redis(options); // 监听和发布
// const pub = new Redis(options); // 监听和发布如果用不同的channel,要再定义一个
const nodeRedis = async () => {
redis.subscribe('channel1', () => { });
redis.on('message', async (channel, message) => {
// message是接收到channel1的信息
// 业务逻辑处理
}
}
// 发布
// const publishInfo = () => {
// pub.publish('channel2', /*这里是要发布到channel2的信息*/);
// }
module.exports = nodeRedis;
使用方法
/*koa端调用:如果是做消息队列发布订阅,写完业务逻辑后,调用方法即可在启动后执行*/
nodeRedis();
/* 如果是普通的set、get,使用如下 */
await redis.set('token', result.access_token);
await redis.get('token', (err, result) => {
ticket = result;
})