关于 laravel:performance-caching
面向 Laravel 的缓存技能,介绍框架缓存以及值和查询结果的缓存方法。内容涵盖键设计、过期时间、失效策略、缓存标签及 Laravel 13+ 的变化。
主要功能
- 01缓存框架路由、配置和视图
- 02缓存值与查询结果
- 03按数据新鲜度设置过期时间
- 04用标签失效相关条目
- 05处理 Laravel 13+ 缓存变化
适用场景
- 01使用 `Cache::remember()` 缓存查询结果
- 02相关写入后清除一组缓存条目
- 03升级 Laravel 时规划缓存前缀
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ jpcaparas/ superpowers-laravel --skill laravel:performance-caching安装后在 Claude Code 中输入/laravel:performance-caching确认已加载。
详细介绍
缓存基础知识
框架缓存
php artisan route:cache
php artisan config:cache
php artisan view:cache
在部署中需要时,使用对应的 clear 命令清除缓存。
值和查询
Cache::remember("post:{$id}", 600, fn () => Post::findOrFail($id));
- 根据新鲜度要求选择 TTL
- 对写入操作进行显式失效处理,确保正确性
模式和策略
// Stable keys and scopes (e.g., tenant, locale)
Cache::remember("tenant:{$tenantId}:users:index:page:1", now()->addMinutes(5), function () {
return User::with('team')->paginate(50);
});
// Tags (supported drivers) for grouped invalidation
Cache::tags(['users'])->remember('users.index.page.1', now()->addMinutes(5), fn () => ...);
Cache::tags(['users'])->flush();
// Locks to ensure exclusive expensive work
Cache::lock('reports:daily', 30)->block(5, function () {
generateReports();
});
- 使用稳定且带命名空间的键;包含所有作用域维度
- 优先使用
remember(),以防止惊群效应 - 使用缓存标签(如果支持),以便一并失效相关条目
- 若无明确计划,避免缓存高度动态或特定于用户的数据
- 在缓存代码旁记录失效触发条件
Laravel 13+
// Extend TTL without re-fetching/re-storing the value
Cache::touch('user_session:123', 3600);
Cache::touch('analytics_data', now()->addHours(6));
// Filesystem-backed "storage" cache driver (e.g., S3 as a K/V store)
// config/cache.php
'storage' => [
'driver' => 'storage',
'disk' => env('CACHE_STORAGE_DISK', 's3'),
'path' => env('CACHE_STORAGE_PATH', 'framework/cache/data'),
],
- 安全默认设置:
config/cache.php中的serializable_classes为false;将需要作为对象缓存的类加入允许列表 - 13.x 中默认缓存/Redis 前缀由下划线改为连字符;显式固定
CACHE_PREFIX/REDIS_PREFIX,避免升级后缓存变冷
评论
支持 Markdown