1. /*redis逻辑处理*/
    2. const Redis = require('ioredis');
    3. const requestConfig = require('../config/redis_config');
    4. const request = require('../utils/request').post;
    5. // 普通模式
    6. // const options = {
    7. // host: requestConfig.redisHost, // Redis host
    8. // port: requestConfig.redisPort1, // Redis port
    9. // }
    10. // 哨兵模式,多端口
    11. const options = {
    12. sentinels: [
    13. {
    14. host: requestConfig.redisHost, // Redis host
    15. port: requestConfig.redisPort1, // Redis port
    16. },
    17. {
    18. host: requestConfig.redisHost, // Redis host
    19. port: requestConfig.redisPort2, // Redis port
    20. },
    21. {
    22. host: requestConfig.redisHost, // Redis host
    23. port: requestConfig.redisPort3, // Redis port
    24. }
    25. ],
    26. name: 'mymaster',
    27. password: requestConfig.redisPwd,
    28. };
    29. const redis = new Redis(options); // 监听和发布
    30. // const pub = new Redis(options); // 监听和发布如果用不同的channel,要再定义一个
    31. const nodeRedis = async () => {
    32. redis.subscribe('channel1', () => { });
    33. redis.on('message', async (channel, message) => {
    34. // message是接收到channel1的信息
    35. // 业务逻辑处理
    36. }
    37. }
    38. // 发布
    39. // const publishInfo = () => {
    40. // pub.publish('channel2', /*这里是要发布到channel2的信息*/);
    41. // }
    42. module.exports = nodeRedis;

    使用方法

    1. /*koa端调用:如果是做消息队列发布订阅,写完业务逻辑后,调用方法即可在启动后执行*/
    2. nodeRedis();
    1. /* 如果是普通的set、get,使用如下 */
    2. await redis.set('token', result.access_token);
    3. await redis.get('token', (err, result) => {
    4. ticket = result;
    5. })