• nodejs bull 实现延时队列


    bull.js

    const Queue = require('bull');
    const queue = new Queue('nike', {
      redis: {
        port: 6379,
        host: '127.0.0.1',
        db: 3,
        password: null
      },
      prefix: 'nike_',
      defaultJobOptions: {
        attempts: 1,
        removeOnComplete: true,
        backoff: false,
        delay: 0
      },
      limiter: {
        max: 200000,
        duration: 1000
      },
      settings: {
        maxStalledCount: 1,
        guardInterval: 1, // 重新调度延迟
        retryProcessDelay: 500, // delay before processing next job in case of internal error.
      // drainDelay: 50000 // 空队列时brpoplpush的等待时间
      }
    });
    module.exports = queue;

    生产者

    const queue = require('./bull');
    const random = require("random-string")
    var log4js = require("log4js");
    var logger = log4js.getLogger();
    logger.level = "info";
    queue.on('global:progress', function(jobId, progress) {
      logger.info(`Job ${jobId} is ${progress * 100}% ready!`);
    });
    queue.on('global:completed', jobId => {
      logger.info(`Job with id ${jobId} has been completed`);
    })
    const  main = async () => {
      for(let i=0;i<10;i++){
        const job = await queue.add({
          key: random(10)
        },{
          delay:5000
        });
        logger.info("生产者:",job.data,await queue.count())
      }
    }
    main()

    消费者

    const queue = require('./bull');
    var log4js = require("log4js");
    var logger = log4js.getLogger();
    logger.level = "info";
    const  main = async () => {
      queue.process(async (job) => {
        logger.info('消费者:',job.data);
         await new Promise(r => setTimeout(r,1000))
        return Promise.resolve();
      });
    }
    main()

     

     

     文档:

    https://github.com/OptimalBits/bull/tree/develop/docs

    api:

    https://github.com/OptimalBits/bull/blob/master/REFERENCE.md#queueprocess

  • 相关阅读:
    函数基础
    全局变量与类似配置文件的模块文件
    global语句(python学习手册422页)
    作用域实例
    变量名解析:LEGB原则
    作用域
    第三方库安装方法
    s[-1]和s[len(s)-1]
    查找特定后缀的文件
    logging日志管理-将日志写入文件
  • 原文地址:https://www.cnblogs.com/xiaosongJiang/p/13047500.html
Copyright © 2020-2023  润新知