缓存使用规范
2026/10/26大约 2 分钟
缓存使用规范
Redis 承载缓存,统一走 app/cache/CacheManager.php,配置在 config/cache_manage.php。已有缓存类:UserInfoCache、UserMenuCache、UserAuthCache、DictCache、ConfigCache、ReflectionCache。
用法
CacheManager 核心方法:
$config = CacheManager::config('user'); // 取某组缓存配置
$data = CacheManager::remember($key, $ttl, fn() => ..., $tags); // 读缓存,未命中回调并写
CacheManager::clearKey($key);
CacheManager::clearTag($tag); // 按标签批量清
CacheManager::clearKeys($prefix, $ids);
CacheManager::clearTags($prefix, $ids);缓存类命名 {Name}Cache.php,提供 getXxx/setXxx/clearXxx/clear()(清整个命名空间),用 remember 包回调。配置分组示例:
'user' => ['tag' => 'atrman:user', 'prefix' => 'atrman:user:info_', 'role' => 'atrman:user:role_', 'expire' => 14400],
'dict' => ['tag' => 'atrman:dict', 'prefix' => 'atrman:dict:', 'expire' => 86400],原则
- 只对读多写少的数据上缓存。
- 更新采用删除策略而非改写策略(清掉让其重建,避免脏值)。
- 批量写后必须清相关缓存。
- 键名有意义、带命名空间前缀,防冲突。
- 合理设过期,不留永久缓存。
- 用标签(按角色、按部门)支持批量清除。
清理时机(对照表)
| 操作 | 需清缓存 |
|---|---|
| 增/改/删用户、改密码、设角色、设部门 | UserInfoCache::clearUserAll($id) |
| 增/改/删角色、分配菜单权限 | UserInfoCache::clearByRole($id)、UserAuthCache::clearByRole($id)、UserMenuCache::clear() |
| 增/改/删菜单 | UserMenuCache::clear()、UserAuthCache::clear()、UserInfoCache::clear() |
| 增/改/删字典 | DictCache::clear() |
反射缓存改注解不生效
Webman 对注解/路由/反射有缓存(app/cache/ReflectionCache.php)。改控制器注解、$noNeedLogin、config/route.php 或特性开关后,必须清反射缓存或重启 worker,否则"改了没反应"。
直接用 support\Redis 时
某些场景会绕过 CacheManager 直接用 support\Redis facade(底层是 illuminate/redis)。设置带过期的 set 要用位置参数:Redis::set($key, $value, 'EX', $ttl, 'NX'),不要写成 phpredis 的数组选项 Redis::set($key, $value, ['NX','EX'=>$ttl]),否则会 TypeError。能走 CacheManager::remember 的优先走它。
