What is @nestjs/bull?
@nestjs/bull is a package for the NestJS framework that provides integration with Bull, a popular library for handling distributed job queues. It allows you to create, manage, and process jobs in a queue, making it useful for background processing, task scheduling, and more.
What are @nestjs/bull's main functionalities?
Creating a Queue
This code demonstrates how to set up a queue named 'my-queue' using the @nestjs/bull package. It configures the connection to a Redis server and registers the queue within a NestJS module.
```typescript
import { BullModule } from '@nestjs/bull';
@Module({
imports: [
BullModule.forRoot({
redis: {
host: 'localhost',
port: 6379,
},
}),
BullModule.registerQueue({
name: 'my-queue',
}),
],
})
export class AppModule {}
```
Adding Jobs to a Queue
This code shows how to add jobs to a queue. The `MyService` class injects the 'my-queue' queue and uses the `addJob` method to add a job with the provided data.
```typescript
import { InjectQueue } from '@nestjs/bull';
import { Queue } from 'bull';
import { Injectable } from '@nestjs/common';
@Injectable()
export class MyService {
constructor(@InjectQueue('my-queue') private readonly myQueue: Queue) {}
async addJob(data: any) {
await this.myQueue.add(data);
}
}
```
Processing Jobs
This code demonstrates how to process jobs in a queue. The `MyQueueProcessor` class is decorated with `@Processor('my-queue')` to indicate it will handle jobs from 'my-queue'. The `handleJob` method processes each job.
```typescript
import { Processor, Process } from '@nestjs/bull';
import { Job } from 'bull';
@Processor('my-queue')
export class MyQueueProcessor {
@Process()
async handleJob(job: Job) {
console.log('Processing job:', job.data);
// Add your job processing logic here
}
}
```
Other packages similar to @nestjs/bull
bull
Bull is a Node.js library for creating and managing job queues. It is the underlying library used by @nestjs/bull. While @nestjs/bull provides integration with the NestJS framework, Bull can be used independently in any Node.js application.
agenda
Agenda is a lightweight job scheduling library for Node.js. It provides similar functionality to Bull but focuses more on job scheduling and recurring tasks. It uses MongoDB as its storage backend, whereas Bull uses Redis.
kue
Kue is another job queue library for Node.js that uses Redis. It provides a simple API for creating and processing jobs, along with a built-in UI for monitoring job status. Kue is less actively maintained compared to Bull.