Node.js

Learn how to connect to Redis databases in Sealos DevBox using Node.js

This guide will walk you through the process of connecting to a Redis database using Node.js within your Sealos DevBox project.

Prerequisites

Install Required Packages

In your Cursor terminal, install the necessary packages:

npm install redis dotenv

This command installs:

  • redis: The Redis client for Node.js
  • dotenv: A zero-dependency module that loads environment variables from a .env file

Connection Setup

Set up the environment variables

First, let's set up the environment variables for our database connection. Create a .env file in your project root with the following content:

.env
REDIS_HOST=your_redis_host
REDIS_PORT=6379
REDIS_PASSWORD=your_redis_password

Replace the placeholders with your actual Redis credentials from the Database app in Sealos.

Create a connection file

Next, create a file named redisClient.js with the following content:

const redis = require('redis');
require('dotenv').config();
 
const client = redis.createClient({
  url: `redis://${process.env.REDIS_HOST}:${process.env.REDIS_PORT}`,
  password: process.env.REDIS_PASSWORD
});
 
client.on('error', (err) => console.log('Redis Client Error', err));
 
async function connectRedis() {
  await client.connect();
}
 
module.exports = { client, connectRedis };

This file creates a Redis client and exports it along with a connection function.

Create a test script

Now, let's create a file named test-redis.js to demonstrate basic Redis operations:

const { client, connectRedis } = require('./redisClient');
 
async function testRedisOperations() {
  try {
    await connectRedis();
    console.log('Connected to Redis');
 
    // Set a key
    await client.set('mykey', 'Hello from Sealos DevBox!');
    console.log('Key set successfully');
 
    // Get a key
    const value = await client.get('mykey');
    console.log('Retrieved value:', value);
 
    // Set a hash
    await client.hSet('myhash', 'field1', 'value1');
    await client.hSet('myhash', 'field2', 'value2');
    console.log('Hash set successfully');
 
    // Get hash fields
    const hashValue = await client.hGetAll('myhash');
    console.log('Retrieved hash:', hashValue);
 
    // Close the connection
    await client.quit();
    console.log('Redis connection closed');
  } catch (error) {
    console.error('An error occurred:', error);
  }
}
 
testRedisOperations();

This script demonstrates setting and getting a key, as well as working with Redis hashes.

Usage

To run the test script, use the following command in your Cursor terminal:

node test-redis.js

This will execute the testRedisOperations function, demonstrating the connection to Redis and basic operations.

Best Practices

  1. Use environment variables for Redis credentials.
  2. Handle connection errors and implement reconnection logic if needed.
  3. Use async/await for cleaner asynchronous code.
  4. Close the Redis connection when it's no longer needed.
  5. Consider using a connection pool for better performance in production environments.

Troubleshooting

If you encounter connection issues:

  1. Verify your Redis credentials in the .env file.
  2. Ensure your Redis database is running and accessible.
  3. Check for any network restrictions in your DevBox environment.
  4. Confirm that the redis package is correctly installed.

For more detailed information on using Redis with Node.js, refer to the Node Redis documentation.

Edit on GitHub

Last updated on

On this page