add Discord Me cache
This commit is contained in:
parent
0393ab8b89
commit
d95d78f5a2
4 changed files with 60 additions and 2 deletions
|
|
@ -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;
|
||||
|
|
|
|||
54
app/Redis.php
Normal file
54
app/Redis.php
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue