Introdução ao Redis - Cache e Gerenciamento de Sessões

Intermediário | 45 min leitura | 2024.12.24

O que você vai aprender neste tutorial

✓ Instalação e operações básicas do Redis
✓ Tipos de dados e comandos
✓ Padrões de cache
✓ Gerenciamento de sessões
✓ Integração com Node.js

Step 1: Configuração

# macOS
brew install redis
brew services start redis

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

# Verificar conexão
redis-cli ping
# PONG

Step 2: Comandos Básicos

# Strings
SET name "Alice"
GET name
SETEX token 3600 "abc123"  # Com tempo de expiração

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

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

# Set
SADD tags "javascript" "typescript"
SMEMBERS tags

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

Step 3: Integração com Node.js

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

const redis = new Redis();

// Função 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;
}

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

Step 4: Gerenciamento de Sessões

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 }
}));

Step 5: Estratégias 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);
}

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

Resumo

Redis é um data store in-memory de alta velocidade, ideal para cache e gerenciamento de sessões. Melhore a performance com configuração adequada de TTL e estratégias de invalidação.

← Voltar para a lista