Node.js 任务队列Bull的源码浅析

本文介绍了Bull,一个基于Redis的Node.js任务队列库,涵盖创建队列、绑定任务处理函数和添加任务的基本用法。在深入源码时,特别关注了任务的执行流程,包括解锁工作(job unlocking)和任务处理。当工作进程被阻塞或崩溃时,可能出现错误,因为这会导致锁过期,使任务变为stalled状态。Bull通过lua脚本来管理job的状态,从active到completed或failed。此外,还探讨了如何通过lua脚本将任务存储到Redis。
摘要由CSDN通过智能技术生成

原文地址: www.jianshu.com/p/1ed50e6d4…

Bull是基于Redis的一个Node.js任务队列管理库,支持延迟队列,优先级任务,重复任务,以及原子操作等多种功能.

本文将从基本的使用来分析Bull的源码,对于repeat job,seperate processes等暂不展开.

Bull: Premium Queue package for handling jobs and messages in NodeJS.

相关的信息如下:

基本使用

Bull的使用分为三个步骤:

  1. 创建队列
  2. 绑定任务处理函数
  3. 添加任务

如下示例:

const Bull = require('bull')
// 1. 创建队列
const myFirstQueue = new Bull('my-first-queue');
// 2. 绑定任务处理函数
myFirstQueue.process(async (job, data) => {
  return doSomething(data);
});
// 3. 添加任务
const job = await myFirstQueue.add({
  foo: 'bar'
});
复制代码

创建队列

创建队列是先通过require然后再通过new来实现的,因此要先找到require的入口.打开package.json:

{
  "name": "bull",
  "version": "3.7.0",
  "description": "Job manager",
  "main": "./index.js",
  ...
}
复制代码

看到入口为index.js,打开:

module.exports = require('./lib/queue');
module.exports.Job = require('./lib/job');
复制代码

从而找到目标函数所在文件./lib/queue:

module.exports = Queue;
复制代码

可以看到exports的是Queue,接着去分析Queue函数:

const Queue = function Queue(name, url, opts) {
  ...
  // 默认设置
  this.settings = _.defaults(opts.settings, { 
    lockDuration: 30000,
    stalledInterval: 30000,
    maxStalledCount: 1,
    guardInterval: 5000,
    retryProcessDelay: 5000,
    drainDelay: 5, // 空队列时brpoplp
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值