优化-实例化奖励列表到缓存中

This commit is contained in:
2026-03-06 14:16:01 +08:00
parent f7d9b18f02
commit 931af70c36
3 changed files with 89 additions and 13 deletions

View File

@@ -7,11 +7,13 @@
namespace app\dice\model\reward_config;
use plugin\saiadmin\basic\think\BaseModel;
use support\think\Cache;
/**
* 奖励配置模型
*
* dice_reward_config 奖励配置
* 奖励列表为全玩家通用,保存时刷新缓存,游戏时优先读缓存。
*
* @property $id ID
* @property $grid_number 色子点数
@@ -24,6 +26,12 @@ use plugin\saiadmin\basic\think\BaseModel;
*/
class DiceRewardConfig extends BaseModel
{
/** 缓存键:全玩家通用的奖励配置列表 */
private const CACHE_KEY_LIST = 'dice:reward_config:list';
/** 缓存过期时间(秒),保存时会主动刷新故设较长 */
private const CACHE_TTL = 86400 * 30;
/**
* 数据表主键
* @var string
@@ -36,6 +44,78 @@ class DiceRewardConfig extends BaseModel
*/
protected $table = 'dice_reward_config';
/**
* 获取缓存的奖励列表(无则从库加载并写入缓存)
* @return array<int, array>
*/
public static function getCachedList(): array
{
$list = Cache::get(self::CACHE_KEY_LIST);
if ($list !== null && is_array($list)) {
return $list;
}
self::refreshCache();
$list = Cache::get(self::CACHE_KEY_LIST);
return is_array($list) ? $list : [];
}
/**
* 重新从数据库加载并写入缓存(保存时调用)
*/
public static function refreshCache(): void
{
$list = (new self())->order('id', 'asc')->select()->toArray();
Cache::set(self::CACHE_KEY_LIST, $list, self::CACHE_TTL);
}
/**
* 从缓存取最小 real_ev
*/
public static function getCachedMinRealEv(): float
{
$list = self::getCachedList();
if (empty($list)) {
return 0.0;
}
$vals = array_column($list, 'real_ev');
$min = min($vals);
return (float) $min;
}
/**
* 从缓存按档位取奖励列表
* @return array<int, array>
*/
public static function getCachedByTier(string $tier): array
{
$list = self::getCachedList();
$rows = [];
foreach ($list as $row) {
if (isset($row['tier']) && (string) $row['tier'] === $tier) {
$rows[] = $row;
}
}
return $rows;
}
/** 保存后刷新缓存 */
public static function onAfterInsert($model): void
{
self::refreshCache();
}
/** 更新后刷新缓存 */
public static function onAfterUpdate($model): void
{
self::refreshCache();
}
/** 删除后刷新缓存 */
public static function onAfterDelete($model): void
{
self::refreshCache();
}
/** 色子点数下限 */
public function searchGridNumberMinAttr($query, $value)
{