Introduccion a Redis - Cache y Gestion de Sesiones

Intermedio | 45 min de lectura | 2024.12.24

Lo que Aprenderas en Este Tutorial

✓ Instalacion y operaciones basicas de Redis
✓ Tipos de datos y comandos de operacion
✓ Patrones de cache
✓ Gestion de sesiones
✓ Integracion con Node.js

Paso 1: Configuracion

# macOS
brew install redis
brew services start redis

# Ubuntu
sudo apt install redis-server
sudo systemctl start redis

# Verificar conexion
redis-cli ping
# PONG

Paso 2: Comandos Basicos

# Strings
SET name "Alice"
GET name
SETEX token 3600 "abc123"  # Con tiempo de expiracion

# Hash
HSET user:1 name "Alice" email "alice@example.com"
HGET user:1 name
HGETALL user:1

# Listas
LPUSH queue "task1"
RPUSH queue "task2"
LPOP queue

# Sets
SADD tags "javascript" "typescript"
SMEMBERS tags

# Sorted Sets
ZADD ranking 100 "alice" 85 "bob"
ZRANGE ranking 0 -1 WITHSCORES

Paso 3: Integracion con Node.js

// npm install ioredis
import Redis from 'ioredis';

const redis = new Redis();

// Funcion de cache
async function getWithCache<T>(
  key: string,
  fetcher: () => Promise<T>,
  ttl: number = 3600
): Promise<T> {
  const cached = await redis.get(key);
  if (cached) {
    return JSON.parse(cached);
  }

  const data = await fetcher();
  await redis.setex(key, ttl, JSON.stringify(data));
  return data;
}

// Ejemplo de uso
const user = await getWithCache(
  `user:${userId}`,
  () => db.user.findById(userId),
  600
);

Paso 4: Gestion de Sesiones

import session from 'express-session';
import RedisStore from 'connect-redis';
import Redis from 'ioredis';

const redis = new Redis();

app.use(session({
  store: new RedisStore({ client: redis }),
  secret: 'your-secret',
  resave: false,
  saveUninitialized: false,
  cookie: { maxAge: 86400000 }
}));

Paso 5: Estrategias de Cache

// Cache-Aside
async function getUser(id: number) {
  const cacheKey = `user:${id}`;
  let user = await redis.get(cacheKey);

  if (!user) {
    user = await db.user.findById(id);
    await redis.setex(cacheKey, 3600, JSON.stringify(user));
  }

  return JSON.parse(user);
}

// Invalidacion de cache
async function updateUser(id: number, data: any) {
  await db.user.update(id, data);
  await redis.del(`user:${id}`);
}

Resumen

Redis es un almacen de datos en memoria de alta velocidad, ideal para cache y gestion de sesiones. Mejora el rendimiento con configuracion apropiada de TTL y estrategias de invalidacion.

← Volver a la lista