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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?