From 90090061f015c6e7ed340694276778a4402b6ca7 Mon Sep 17 00:00:00 2001 From: Alexey Skobkin Date: Sun, 5 Jul 2020 04:19:27 +0300 Subject: [PATCH] Implementing simple Redis cache for RSS. --- .env | 3 +++ config/packages/framework.yaml | 6 ++++++ src/Api/V1/Controller/RssController.php | 12 ++++++++++-- 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/.env b/.env index 897f242..228b2c0 100644 --- a/.env +++ b/.env @@ -17,6 +17,9 @@ APP_DATABASE_URL=postgres://$PGUSER:$PGPASSWORD@127.0.0.1:5436/test?application_ MAGNETICOD_DATABASE_URL=postgres://$PGUSER:$PGPASSWORD@127.0.0.1:5436/test?application_name=magnetico_web ###< doctrine/doctrine-bundle ### +# Redis cache +REDIS_DSN=redis://127.0.0.1:6379/0 + ###> sentry/sentry-symfony ### SENTRY_DSN= ###< sentry/sentry-symfony ### diff --git a/config/packages/framework.yaml b/config/packages/framework.yaml index 8b24418..9d351c2 100644 --- a/config/packages/framework.yaml +++ b/config/packages/framework.yaml @@ -28,3 +28,9 @@ framework: # APCu (not recommended with heavy random-write workloads as memory fragmentation can cause perf issues) #app: cache.adapter.apcu + prefix_seed: magnetico-web + pools: + magneticod.cache: + adapter: cache.adapter.redis + provider: '%env(REDIS_DSN)%' + default_lifetime: 600 diff --git a/src/Api/V1/Controller/RssController.php b/src/Api/V1/Controller/RssController.php index 5fd4659..9534f94 100644 --- a/src/Api/V1/Controller/RssController.php +++ b/src/Api/V1/Controller/RssController.php @@ -5,16 +5,24 @@ namespace App\Api\V1\Controller; use App\Feed\RssGenerator; use Symfony\Component\HttpFoundation\{Request, Response}; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; +use Symfony\Contracts\Cache\CacheInterface; +use Symfony\Contracts\Cache\ItemInterface; class RssController extends AbstractController { private const CONTENT_TYPE = 'application/rss+xml'; + private const CACHE_KEY = 'rss_last'; + private const CACHE_LIFETIME = 600; - public function last(Request $request, RssGenerator $generator): Response + public function last(Request $request, RssGenerator $generator, CacheInterface $magneticodCache): Response { $page = (int) $request->query->get('page', '1'); - $xml = $generator->generateLast($page); + $xml = $magneticodCache->get(self::CACHE_KEY, function (ItemInterface $item) use ($generator, $page) { + $item->expiresAfter(self::CACHE_LIFETIME); + + return $generator->generateLast($page); + }); return new Response($xml, 200, ['Content-Type' => self::CONTENT_TYPE]); }