关于 laravel-caching-strategies
面向 Laravel 开发者的缓存模式技能,介绍应用数据和查询的缓存方式,涵盖过期策略、分组失效、锁、记忆化、键命名规范及常见问题。
主要功能
- 01按时限或永久缓存数据
- 02通过标签失效相关条目
- 03用原子锁保护独占操作
- 04在请求期间记忆化数据
- 05采用一致的缓存键命名规范
- 06处理空值结果及缓存问题
适用场景
- 01缓存开销较大的数据库查询
- 02数据变更后清除相关缓存
- 03防止同一操作被并发处理
- 04减少请求内重复的缓存查找
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ iserter/ laravel-claude-agents --skill laravel-caching-strategies安装后在 Claude Code 中输入/laravel-caching-strategies确认已加载。
详细介绍
Laravel 缓存策略
核心缓存模式
use Illuminate\Support\Facades\Cache;
// ✅ remember - cache for a duration
$users = Cache::remember('users:active', now()->addMinutes(30), function () {
return User::where('active', true)->get();
});
// ✅ rememberForever - cache until manually cleared
$settings = Cache::rememberForever('app:settings', function () {
return Setting::all()->pluck('value', 'key');
});
// ✅ flexible - stale-while-revalidate pattern
// Fresh for 5 min, serves stale for up to 15 min while revalidating in background
$stats = Cache::flexible('dashboard:stats', [300, 900], function () {
return DashboardStats::calculate();
});
// ✅ put / get / forget
Cache::put('key', $value, now()->addHours(1));
$value = Cache::get('key', 'default');
Cache::forget('key');
// ❌ Querying the database when cache would suffice
$settings = Setting::all(); // Every request hits the DB
使用缓存标签进行分组失效
// ✅ Tag related cache entries
Cache::tags(['posts', 'users'])->put("user:{$userId}:posts", $posts, 3600);
Cache::tags(['posts'])->put("post:{$postId}", $post, 3600);
Cache::tags(['users'])->put("user:{$userId}:profile", $profile, 3600);
// ✅ Flush all caches for a tag group
Cache::tags(['posts'])->flush(); // Clears all post-related caches
// ✅ Retrieve tagged cache
$posts = Cache::tags(['posts', 'users'])->get("user:{$userId}:posts");
// Note: Cache tags are only supported by redis and memcached drivers
原子锁
use Illuminate\Support\Facades\Cache;
// ✅ Prevent concurrent execution
$lock = Cache::lock('processing:order:' . $orderId, 10); // 10 second lock
if ($lock->get()) {
try {
// Process order exclusively
$this->processOrder($orderId);
} finally {
$lock->release();
}
}
// ✅ Block and wait for lock (up to 5 seconds)
$lock = Cache::lock('report:generate', 30);
$lock->block(5, function () {
// Acquired lock, do work
$this->generateReport();
}); // Lock auto-released after closure
// ✅ Cross-process lock with owner token
$lock = Cache::lock('deployment', 120);
if ($lock->get()) {
$owner = $lock->owner();
// Pass $owner to another process
}
// In the other process
Cache::restoreLock('deployment', $owner)->release();
// ❌ Forgetting to release locks
$lock->get();
$this->doWork(); // If this throws, lock is never released
缓存记忆化
use Illuminate\Support\Facades\Cache;
// ✅ memo - in-memory cache for the current request lifecycle
// Avoids repeated cache store lookups within the same request
$config = Cache::memo('app:config', function () {
return Config::loadFromDatabase();
});
// Subsequent calls return the in-memory value without hitting Redis/Memcached
$config = Cache::memo('app:config', fn () => Config::loadFromDatabase());
模型缓存模式
class Product extends Model
{
// ✅ Cache on read with automatic invalidation
public static function findCached(int $id): ?self
{
return Cache::remember(
"product:{$id}",
now()->addHour(),
fn () => static::find($id)
);
}
// ✅ Invalidate cache on model changes
protected static function booted(): void
{
static::saved(function (Product $product) {
Cache::forget("product:{$product->id}");
Cache::tags(['products'])->flush();
});
static::deleted(function (Product $product) {
Cache::forget("product:{$product->id}");
Cache::tags(['products'])->flush();
});
}
}
// ✅ Cache query results with tags for group invalidation
class ProductService
{
public function getFeatured(): Collection
{
return Cache::tags(['products'])->remember(
'products:featured',
now()->addMinutes(30),
fn () => Product::where('featured', true)->with('category')->get()
);
}
}
缓存键约定
// ✅ Use consistent, descriptive key patterns
"user:{$userId}:profile"
"post:{$postId}:comments:page:{$page}"
"tenant:{$tenantId}:settings"
"api:github:repos:{$username}"
"report:daily:{$date}"
// ✅ Include cache-busting identifiers when data shape changes
"v2:user:{$userId}:profile"
// ❌ Vague or collision-prone keys
"data"
"user"
"temp"
"cache_1"
常见问题
// ❌ Caching null results without handling them
$user = Cache::remember("user:{$id}", 3600, fn () => User::find($id));
// If user doesn't exist, null is cached for an hour
// ✅ Handle null explicitly
$user = Cache::remember("user:{$id}", 3600, function () use ($id) {
return User::find($id) ?? new NullUser();
});
// ❌ No invalidation strategy
Cache::forever('products:all', Product::all());
// Data becomes stale with no way to refresh
// ✅ Use TTL or event-based invalidation
Cache::remember('products:all', now()->addMinutes(15), fn () => Product::all());
// ❌ Caching too aggressively (serialization cost > query cost)
Cache::remember('user:count', 3600, fn () => User::count());
// Simple COUNT queries are often fast enough without caching
// ✅ Cache expensive operations
Cache::remember('dashboard:analytics', 3600, function () {
return DB::table('orders')
->selectRaw('DATE(created_at) as date, SUM(total) as revenue')
->groupByRaw('DATE(created_at)')
->orderBy('date')
->get();
});
// ❌ Cache stampede - many requests regenerate cache simultaneously
// ✅ Use flexible() for stale-while-revalidate or atomic locks for regeneration
检查清单
- 使用 remember/rememberForever,而不是手动调用 get/put
- 对能够容忍短暂过期的高流量键使用 flexible()
- 使用缓存标签进行分组失效(仅限 Redis/Memcached)
- 对需要独占执行的操作使用原子锁
- 在保存/删除事件中使模型缓存失效
- 遵循一致的缓存键命名约定
- 适当设置 TTL(既不要太长,也不要太短)
- 处理 null/空结果,避免缓存无内容
- 缓存开销较大的查询,不缓存简单查询
- 使用 flexible() 或锁防止缓存雪崩
评论
支持 Markdown