1.优化getPlayerInfo接口
This commit is contained in:
61
server/app/api/cache/UserCache.php
vendored
61
server/app/api/cache/UserCache.php
vendored
@@ -238,6 +238,17 @@ class UserCache
|
||||
return (int) config('api.player_cache_ttl', 300);
|
||||
}
|
||||
|
||||
/** /api/v1/getPlayerInfo 快照 key 前缀 */
|
||||
private static function playerInfoSnapshotPrefix(): string
|
||||
{
|
||||
return config('api.player_info_snapshot_prefix', 'api:v1:player_info:');
|
||||
}
|
||||
|
||||
private static function playerInfoSnapshotTtl(): int
|
||||
{
|
||||
return (int) config('api.player_info_snapshot_ttl', 180);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 username 缓存玩家信息(仅 id + username,供中间件注入 request->player 后使用)
|
||||
* 登录/信息变更时需调用 deletePlayerByUsername 失效
|
||||
@@ -280,6 +291,54 @@ class UserCache
|
||||
return false;
|
||||
}
|
||||
$key = self::playerCachePrefix() . $username;
|
||||
return Cache::delete($key);
|
||||
$r1 = Cache::delete($key);
|
||||
$snapKey = self::playerInfoSnapshotPrefix() . $username;
|
||||
$r2 = Cache::delete($snapKey);
|
||||
return $r1 || $r2;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取 getPlayerInfo 接口用的玩家公开信息快照(未命中返回 null)
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
public static function getPlayerInfoSnapshotByUsername(string $username): ?array
|
||||
{
|
||||
if ($username === '') {
|
||||
return null;
|
||||
}
|
||||
if (self::playerInfoSnapshotTtl() <= 0) {
|
||||
return null;
|
||||
}
|
||||
$key = self::playerInfoSnapshotPrefix() . $username;
|
||||
$val = Cache::get($key);
|
||||
if ($val === null || $val === '') {
|
||||
return null;
|
||||
}
|
||||
$data = json_decode((string) $val, true);
|
||||
if (!is_array($data) || !array_key_exists('username', $data)) {
|
||||
return null;
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入 getPlayerInfo 返回体快照(已脱敏数组)
|
||||
* @param array<string, mixed> $info
|
||||
*/
|
||||
public static function setPlayerInfoSnapshotByUsername(string $username, array $info): bool
|
||||
{
|
||||
if ($username === '' || empty($info)) {
|
||||
return false;
|
||||
}
|
||||
$ttl = self::playerInfoSnapshotTtl();
|
||||
if ($ttl <= 0) {
|
||||
return true;
|
||||
}
|
||||
$key = self::playerInfoSnapshotPrefix() . $username;
|
||||
$payload = json_encode($info, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
|
||||
if ($payload === false) {
|
||||
return false;
|
||||
}
|
||||
return Cache::set($key, $payload, $ttl);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user