2.4.2.2 Connection & Basic Usage

// backend/src/config/redisClient.js
const { createClient } = require('redis');

const redisClient = createClient({
  url: process.env.REDIS_URL || 'redis://localhost:6379'
});

redisClient.on('error', (err) => console.error('Redis Error:', err));

(async () => {
  await redisClient.connect();
  console.log('Redis connected');
})();

module.exports = redisClient;

Example: Caching market data

const redisClient = require('../config/redisClient');

async function getCachedPrice(coin) {
  const cacheKey = `price:${coin}`;
  const cached = await redisClient.get(cacheKey);
  if (cached) return JSON.parse(cached);

  // otherwise fetch from external API
  // then store in Redis
  // redisClient.set(cacheKey, JSON.stringify(data), { EX: 60 });
}

Last updated