add Discord Me cache

This commit is contained in:
小喵 2023-08-27 21:53:01 +08:00
parent 0393ab8b89
commit d95d78f5a2
Signed by: mt
GPG key ID: CD321C269EC63BB6
4 changed files with 60 additions and 2 deletions

View file

@ -128,7 +128,9 @@ HTML,
try { try {
$u = static::getU(); $u = static::getU();
if ($u === null) return null; 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) { } catch (Exception) {
error_log('Failed to getMe.'); error_log('Failed to getMe.');
return null; return null;

54
app/Redis.php Normal file
View file

@ -0,0 +1,54 @@
<?php
namespace MingTsay\Akanyan;
use MingTsay\Akanyan\Discord\Me;
require_once __DIR__ . '/../env.php';
class Redis
{
public const PREFIX = 'akanyan:discord:me:';
public const TTL = 600; // 10 minutes
protected static ?\Redis $redis = null;
/**
* @throws \RedisException
*/
protected static function connect(): \Redis
{
if (static::$redis === null) {
static::$redis = new \Redis();
static::$redis->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;
}
}
}

View file

@ -11,6 +11,7 @@
], ],
"require": { "require": {
"ext-iconv": "*", "ext-iconv": "*",
"ext-redis": "*",
"ext-sodium": "*", "ext-sodium": "*",
"ext-zlib": "*", "ext-zlib": "*",
"components/font-awesome": "^6.1", "components/font-awesome": "^6.1",

3
composer.lock generated
View file

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "528c716c3d44b77191eaef0461fe108d", "content-hash": "94e36763cae319a07395535f9c2373eb",
"packages": [ "packages": [
{ {
"name": "components/font-awesome", "name": "components/font-awesome",
@ -734,6 +734,7 @@
"prefer-lowest": false, "prefer-lowest": false,
"platform": { "platform": {
"ext-iconv": "*", "ext-iconv": "*",
"ext-redis": "*",
"ext-sodium": "*", "ext-sodium": "*",
"ext-zlib": "*" "ext-zlib": "*"
}, },