DEV Community

JohnDotOwl
JohnDotOwl

Posted on

Connecting to Redis v4 using Node.js

Redis is an incredibly fast, in-memory data structure store primarily used as a database, cache, and message broker. As with all software, Redis continues to evolve, bringing us to the recent release of Node Redis v4. This release introduces breaking changes and significant refactoring.

Let's look at how you can connect to Redis v4 using Node.js and highlight some major changes from version 3 to version 4.

Basic Connection:

import { createClient } from "redis";

const redisClient = createClient({
  url: "redis://0.0.0.0:6379",
  password: "Password",
});

// Make sure to initiate the connection
await redisClient.connect();

// Example of popping a message from a list
while (true) {
  const message = await redisClient.lPop("crawlowl.com");

  if (message) {
    // Fetch HTTP
    const url = `http://crawlowl.com?param=${message}`;
    const response = await fetch(url);
    const data = await response.text();

    console.log(`Fetched data from ${url}:`, data);
  } else {
    console.log("No messages to process, waiting...");
    await new Promise((resolve) => setTimeout(resolve, 10000));
  }
}

Enter fullscreen mode Exit fullscreen mode

v3 to v4 Migration Guide:

1. Promises:

Version 4 of Node Redis fully embraces modern JavaScript features by making use of native Promises for all its functions. This provides a more consistent and clean approach to handling async operations.

2. createClient:

The configuration object for the createClient function has changed significantly. Most notably, there's no auto-connect feature in v4. You must explicitly connect after creating a client.

3. Events Update:

Several events from v3 have been removed in v4. For instance, message, subscribe, and warning are no longer available. Instead of relying on events for messages, you can now get messages directly from subscription-like commands.

4. No Auto Connect:

Always remember to call .connect() after creating the client. Not doing so will result in a ClientClosedError.

5. No message-like event:

In the previous versions, you'd typically listen to events to handle messages. V4 changes this approach, allowing you to get messages directly in the subscribe-like commands.

const subscriber = createClient();

await subscriber.connect();

await subscriber.subscribe('channel_name', (message, channelName) => {
    console.info(message, channelName);
});

Enter fullscreen mode Exit fullscreen mode

6. Legacy Mode:

If you have an existing codebase and want to move to v4 without making extensive changes, you can use the legacy mode. This mode ensures backward compatibility while still giving access to the updated experience.

const client = createClient({
    legacyMode: true
});

// In legacy mode
client.set('key', 'value', 'NX', (err, reply) => {
    // handle result
});

// V4 interface is still accessible
await client.v4.set('key', 'value', {
    NX: true
});

Enter fullscreen mode Exit fullscreen mode

Conclusion:

Migrating to Node Redis v4 may seem challenging at first, but the updates make the library more aligned with modern JavaScript standards. Embracing these changes can lead to cleaner, more maintainable code. Always remember to test extensively when migrating to ensure that your application functions as expected.

I hope this example code would save you time from googling as there isn't much examples available out there as of September 2023

Top comments (0)