Retour au blog
DevOps

Stratégies de cache avec Redis

30 Aug 2024 8 min
Redis Cache Performance

Redis : stratégies de cache avancées

Redis est bien plus qu'un simple cache clé-valeur. Voici les stratégies pour en tirer le maximum.

Patterns de cache

Cache-Aside (Lazy Loading)

class ProductService
{
    public function getProduct(int $id): Product
    {
        $cacheKey = "product:{$id}";
        $cached = $this->redis->get($cacheKey);

        if ($cached !== null) {
            return unserialize($cached);
        }

        $product = $this->repository->find($id);
        $this->redis->setex($cacheKey, 3600, serialize($product));

        return $product;
    }
}

Write-Through

public function updateProduct(Product $product): void
{
    $this->repository->save($product);
    $this->redis->setex(
        "product:{$product->getId()}",
        3600,
        serialize($product)
    );
}

Cache avec Symfony

# config/packages/cache.yaml
framework:
    cache:
        pools:
            app.cache.products:
                adapter: cache.adapter.redis
                default_lifetime: 3600
                provider: 'redis://redis:6379'
class ProductController
{
    public function list(CacheInterface $productsCache): Response
    {
        $products = $productsCache->get('products_list', function (ItemInterface $item) {
            $item->expiresAfter(3600);
            $item->tag(['products']);
            return $this->repository->findAll();
        });

        return $this->json($products);
    }
}

Invalidation du cache

  • TTL : expiration automatique après un délai
  • Tags : invalidation par groupe avec les tags Symfony
  • Events : invalidation sur événement Doctrine
  • Versioning : clés de cache versionnées