TypeScript 任务队列:Bull、Agenda 和 Bee-Queue

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

TypeScript 任务队列:Bull、Agenda 和 Bee-Queue



在现代 TypeScript 网页应用中,经常需要异步执行资源密集型或长时间运行的操作,以避免阻塞主线程。任务队列(Job Queues)是一种经过验证的架构模式,它允许延迟任务执行、在工作进程之间分配负载并确保处理可靠性。在本文中,我们将探讨三种流行的 TypeScript 工具:Bull、Agenda 和 Bee-Queue。您将了解如何将它们集成到项目中,它们的优势是什么,以及针对特定场景应选择哪种工具。



1. Bull — 基于 Redis 的强大队列



Bull 可以说是 Node.js/TypeScript 中最流行的任务队列管理库。它使用 Redis 作为后端,从而提供高性能和故障恢复能力。Bull 支持任务优先级、重试、延迟,以及暂停和恢复队列等复杂场景。



安装:

npm install bullnpm install @types/bull  // 用于 TypeScript


简单的生产者-消费者示例:

import Queue from 'bull';

// 创建一个名为 'email' 的队列const emailQueue = new Queue('email', { redis: { host: 'localhost', port: 6379 }});

// Producer: 添加任务async function sendWelcomeEmail(userId: string) { await emailQueue.add( { userId, type: 'welcome' }, { attempts: 3, backoff: 2000 } // 3 次尝试,间隔 2 秒 );}

// Consumer: 处理任务emailQueue.process(async (job) => { const { userId, type } = job.data; console.log(`向用户 ${userId} 发送 ${type} 邮件`); // 此处为发送邮件的逻辑});


Bull 还通过 bull-board 或 bull-repl 提供便捷的 UI 监控,简化了生产环境中的调试。



2. Agenda — 支持计划任务的灵活队列



Agenda 是一个同样使用 MongoDB 作为存储的库。其主要特点是内置支持周期性任务(类似 cron 的计划任务)和用于定义重复工作的便捷 API。Agenda 非常适合需要按计划执行的任务:数据库清理、报告生成、摘要发送等。



安装:

npm install agendanpm install @types/agenda


带计划任务的示例:

import Agenda from 'agenda';

const agenda = new Agenda({ db: { address: 'mongodb://localhost:27017/agenda-example' }});

// 定义任务agenda.define('send weekly report', async (job) => { const { department } = job.attrs.data; console.log(`为 ${department} 部门生成周报`);});

// 启动代理并计划任务(async () => { await agenda.start(); // 每周五 18:00 执行 await agenda.every('0 18 * * 5', 'send weekly report', { department: 'IT' });})();


Agenda 支持优先级、重试和优雅关闭。然而,由于使用 MongoDB 而非 Redis,其性能不如 Bull。



3. Bee-Queue — 轻量且快速的队列



Bee-Queue 是一个基于 Redis 的极简队列,专注于最大化性能和最小化代码体积。它不支持优先级或计划任务等复杂功能,但非常适合注重速度和低内存占用的简单场景。



安装:

npm install bee-queuenpm install @types/bee-queue


工作示例:

import Bee from 'bee-queue';

const imageQueue = new Bee('image-processing', { redis: { host: 'localhost', port: 6379 }});

// ProducerimageQueue.createJob({

推荐