How to implements a fast and robust queue system in Nodejs
Queue system using bullmq library.
Install using npm:
npm install bullmq
Create file called job.ts add following code.
import { Injectable } from ‘@nestjs/common’;
import { Queue } from ‘bullmq’;
@Injectable()
export class BullmqService {
public async addJob() {
const queue = new Queue(‘my-queue’);
queue.add(‘cars1’, { color: ‘blue’ });
queue.add(‘cars2’, { color: ‘red’ });
queue.add(‘cars3’, { color: ‘yello’ });
queue.add(‘cars4’, { color: ‘pink’ });
}
}
Process the job from queue using worker
import { Worker } from ‘bullmq’;
const worker = new Worker(‘my-queue’, async job => {
if (job.name) {
console.log(‘==========>’, job.data);
}
});
To see full demo of bullmq with nestjs on github: https://github.com/satishkumarmali/NestJs-BullMQ-Demo