How to Use Bull Queue in NestJS: Simple Guide
To use
Bull queue in NestJS, install @nestjs/bull and bull packages, then import BullModule in your module with queue configuration. Create a processor class with @Processor decorator to handle jobs and add jobs to the queue using Queue service injected via @InjectQueue.Syntax
Using Bull in NestJS involves three main parts:
- Importing BullModule: Register your queue with configuration.
- Creating a Processor: Use
@Processor('queueName')to define job handlers. - Adding Jobs: Inject
Queueand useadd()to enqueue jobs.
typescript
import { BullModule } from '@nestjs/bull'; import { Module } from '@nestjs/common'; @Module({ imports: [ BullModule.forRoot({ redis: { host: 'localhost', port: 6379 }, }), BullModule.forFeature([{ name: 'myQueue' }]), ], }) export class AppModule {} import { Processor, Process } from '@nestjs/bull'; import { Job } from 'bull'; @Processor('myQueue') export class MyProcessor { @Process() async handleJob(job: Job) { // job processing logic } } import { InjectQueue } from '@nestjs/bull'; import { Queue } from 'bull'; export class SomeService { constructor(@InjectQueue('myQueue') private myQueue: Queue) {} async addJob(data: any) { await this.myQueue.add(data); } }
Example
This example shows a NestJS module that sets up a Bull queue named email. It includes a processor that logs job data and a service that adds jobs to the queue.
typescript
import { Module } from '@nestjs/common'; import { BullModule, Processor, Process, InjectQueue } from '@nestjs/bull'; import { Queue } from 'bull'; @Processor('email') export class EmailProcessor { @Process() async handleEmailJob(job: any) { console.log('Processing email job:', job.data); } } export class EmailService { constructor(@InjectQueue('email') private emailQueue: Queue) {} async sendEmail(emailData: { to: string; subject: string; body: string }) { await this.emailQueue.add(emailData); } } @Module({ imports: [ BullModule.forRoot({ redis: { host: 'localhost', port: 6379 }, }), BullModule.forFeature([{ name: 'email' }]), ], providers: [EmailProcessor, EmailService], }) export class AppModule {} // Usage example (e.g., in a controller or service): // await emailService.sendEmail({ to: 'user@example.com', subject: 'Hello', body: 'Welcome!' });
Output
Processing email job: { to: 'user@example.com', subject: 'Hello', body: 'Welcome!' }
Common Pitfalls
Common mistakes when using Bull in NestJS include:
- Not importing
BullModule.forRoot()with Redis config, causing connection errors. - Forgetting to register the queue with
BullModule.forFeature(). - Not using
@Processordecorator on the processor class, so jobs are not processed. - Injecting
Queuewith wrong queue name or missing@InjectQueue. - Not awaiting
queue.add(), which can cause lost jobs.
typescript
/* Wrong: Missing BullModule.forRoot() */ @Module({ imports: [ BullModule.forFeature([{ name: 'task' }]), ], }) export class TaskModule {} /* Right: Include Redis config */ @Module({ imports: [ BullModule.forRoot({ redis: { host: 'localhost', port: 6379 } }), BullModule.forFeature([{ name: 'task' }]), ], }) export class TaskModule {}
Quick Reference
Remember these key points when using Bull in NestJS:
- Use
BullModule.forRoot()once with Redis settings. - Register each queue with
BullModule.forFeature(). - Define processors with
@Processor('queueName')and@Process(). - Inject queues with
@InjectQueue('queueName')to add jobs. - Always await
queue.add()to ensure job is queued.
Key Takeaways
Always configure BullModule.forRoot() with Redis connection before using queues.
Register queues with BullModule.forFeature() to use them in your module.
Use @Processor and @Process decorators to handle jobs in a processor class.
Inject queues with @InjectQueue to add jobs from services or controllers.
Await queue.add() calls to ensure jobs are properly added to the queue.