0
0
Node.jsframework~5 mins

Redis for distributed caching in Node.js

Choose your learning style9 modes available
Introduction

Redis helps store data temporarily so many computers can share it fast. It makes apps quicker by avoiding repeated work.

When you want to speed up a website by saving data that many users need.
When multiple servers need to share the same data quickly.
When you want to reduce load on a slow database by caching results.
When you want to store session info for users in a web app.
When you want to keep temporary data that expires automatically.
Syntax
Node.js
import { createClient } from 'redis';

const client = createClient({ url: 'redis://localhost:6379' });

await client.connect();

// Set a value
await client.set('key', 'value');

// Get a value
const value = await client.get('key');

// Disconnect
await client.disconnect();

Use createClient to connect to Redis server.

Use set and get to store and retrieve data.

Examples
Store and retrieve a JavaScript object by converting it to a string.
Node.js
await client.set('user:1', JSON.stringify({ name: 'Alice', age: 30 }));
const user = JSON.parse(await client.get('user:1'));
Set a key that automatically expires after 10 seconds.
Node.js
await client.set('tempKey', '123', { EX: 10 }); // expires in 10 seconds
Check if a key exists in Redis.
Node.js
const exists = await client.exists('someKey');
Sample Program

This program connects to Redis, saves a user object, then reads and prints it. It shows how Redis can cache data for quick access.

Node.js
import { createClient } from 'redis';

async function run() {
  const client = createClient({ url: 'redis://localhost:6379' });
  client.on('error', (err) => console.log('Redis Client Error', err));

  await client.connect();

  // Save user data
  await client.set('user:100', JSON.stringify({ name: 'Bob', score: 42 }));

  // Retrieve user data
  const data = await client.get('user:100');
  if (data) {
    const user = JSON.parse(data);
    console.log(`User ${user.name} has score ${user.score}`);
  } else {
    console.log('User not found');
  }

  await client.disconnect();
}

run();
OutputSuccess
Important Notes

Make sure Redis server is running locally or update the URL to your Redis host.

Always handle errors when connecting or using Redis.

Use JSON.stringify and JSON.parse to store complex data types.

Summary

Redis stores data in memory for fast access across multiple servers.

Use Redis to cache data and reduce slow database calls.

Node.js uses the official Redis client with async/await for easy coding.