DEV Community

Shrihari Mohan
Shrihari Mohan

Posted on

Redis + πŸ‚ Bull = Easy Background Jobs in nodeJs

Real world use cases why you should use redis in your apps.

Job processing: You could use Redis and Bull to process image uploads, generate PDFs, send emails in background.

Task scheduling: Just like crons.

Caching: cache slow running queries and also api responses.

Real-time updates: Redis can be used to publish and subscribe to messages, making it a great tool for implementing real-time updates in Node.js applications.

Rate limiting: You could use Redis to limit the number of API requests a user can make in a given time period.

Setting up redis

For windows
you can directly Download this and run the redis-server inside bin folder or use of wsl2 the Official way

For Linux
If your linux supports snap then its simple Or follow these simple steps from Offical Docs

sudo snap install redis
Enter fullscreen mode Exit fullscreen mode

For mac

brew install redis
redis-server
Enter fullscreen mode Exit fullscreen mode

If you want to know more

By default the redis will start in redis://localhost:6379

Setting up NodeJs

Hope you have a sample nodeJs template
Add bull to the dependenceis.

npm install bull
yarn add bull
Enter fullscreen mode Exit fullscreen mode

Create Jobs.

import express from 'express'
import Queue from 'bull'

const myQueue = new Queue('test-queue', 'redis://localhost:6379');
const app = express()
const port = 3000

let count = 1

app.get('/', async (req, res) => {
  // Add jobs to the queue
  await myQueue.add({ data: { count: count++ } });
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)

})

// process jobs from the queue 
myQueue.process(async (job) => {
  console.log(`Processing job ${job.id} with data `, job.data);
  return Promise.resolve();
});

Enter fullscreen mode Exit fullscreen mode

Thats it you are done. All you have to do is hit the apis to schedule a job and myQueue will keep on logging.

Make sure your redis is up and running , redis url is connect.

Sample Out

Peace πŸ•Š


If you are here it means you may have found this blog helpful. Just follow me @shrihari which will motivate to write more. You can make a Buttermilk πŸ₯›. Small support comes a long way!

Subscribe If you want to receive these blogs in your mail from @Medium for free!

More things from me

Top comments (0)