From d95d78f5a261fbf97f422d6e5c14b496620bedaf Mon Sep 17 00:00:00 2001 From: Ming Tsay Date: Sun, 27 Aug 2023 21:53:01 +0800 Subject: [PATCH] add Discord Me cache --- app/App.php | 4 +++- app/Redis.php | 54 +++++++++++++++++++++++++++++++++++++++++++++++++++ composer.json | 1 + composer.lock | 3 ++- 4 files changed, 60 insertions(+), 2 deletions(-) create mode 100644 app/Redis.php diff --git a/app/App.php b/app/App.php index d10c3e5..f05f3ff 100644 --- a/app/App.php +++ b/app/App.php @@ -128,7 +128,9 @@ HTML, try { $u = static::getU(); if ($u === null) return null; - return Auth::getMe($u); + $cachedMe = Redis::getCachedMe($_COOKIE['u']); + if ($cachedMe === null) return Redis::cacheMe($_COOKIE['u'], Auth::getMe($u)); + return $cachedMe; } catch (Exception) { error_log('Failed to getMe.'); return null; diff --git a/app/Redis.php b/app/Redis.php new file mode 100644 index 0000000..5981b3c --- /dev/null +++ b/app/Redis.php @@ -0,0 +1,54 @@ +connect('127.0.0.1'); + } + return static::$redis; + } + + protected static function getKey(string $u): string + { + return static::PREFIX . md5($u); + } + + public static function getCachedMe(string $u): ?Me + { + try { + $redis = static::connect(); + return unserialize($redis->get(static::getKey($u))) ?: null; + } catch (\RedisException $e) { + trigger_error($e->getMessage()); + return null; + } + } + + public static function cacheMe(string $u, ?Me $me): ?Me + { + try { + $redis = static::connect(); + $redis->setEx(static::getKey($u), static::TTL, serialize($me)); + return $me; + } catch (\RedisException $e) { + trigger_error($e->getMessage()); + return null; + } + } +} diff --git a/composer.json b/composer.json index 489df28..2426099 100644 --- a/composer.json +++ b/composer.json @@ -11,6 +11,7 @@ ], "require": { "ext-iconv": "*", + "ext-redis": "*", "ext-sodium": "*", "ext-zlib": "*", "components/font-awesome": "^6.1", diff --git a/composer.lock b/composer.lock index 4a443b7..47588c1 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "528c716c3d44b77191eaef0461fe108d", + "content-hash": "94e36763cae319a07395535f9c2373eb", "packages": [ { "name": "components/font-awesome", @@ -734,6 +734,7 @@ "prefer-lowest": false, "platform": { "ext-iconv": "*", + "ext-redis": "*", "ext-sodium": "*", "ext-zlib": "*" },