优化性能

This commit is contained in:
2026-03-05 17:20:44 +08:00
parent effdaaa38b
commit 005f261e03
12 changed files with 99 additions and 28 deletions

View File

@@ -226,4 +226,60 @@ class UserCache
$key = self::sessionUsernamePrefix() . $username;
return Cache::delete($key);
}
/** 玩家缓存 key 前缀Token 中间件用,减少重复查库) */
private static function playerCachePrefix(): string
{
return config('api.player_cache_prefix', 'api:player:');
}
private static function playerCacheTtl(): int
{
return (int) config('api.player_cache_ttl', 300);
}
/**
* 按 username 缓存玩家信息(仅 id + username供中间件注入 request->player 后使用)
* 登录/信息变更时需调用 deletePlayerByUsername 失效
*/
public static function setPlayerByUsername(string $username, array $playerRow): bool
{
if ($username === '' || empty($playerRow)) {
return false;
}
$ttl = self::playerCacheTtl();
if ($ttl <= 0) {
return true;
}
$key = self::playerCachePrefix() . $username;
return Cache::set($key, json_encode($playerRow), $ttl);
}
/** 按 username 取缓存玩家,未命中返回 null */
public static function getPlayerByUsername(string $username): ?array
{
if ($username === '') {
return null;
}
if (self::playerCacheTtl() <= 0) {
return null;
}
$key = self::playerCachePrefix() . $username;
$val = Cache::get($key);
if ($val === null || $val === '') {
return null;
}
$data = json_decode((string) $val, true);
return is_array($data) ? $data : null;
}
/** 退出登录或玩家信息变更时删除玩家缓存 */
public static function deletePlayerByUsername(string $username): bool
{
if ($username === '') {
return false;
}
$key = self::playerCachePrefix() . $username;
return Cache::delete($key);
}
}