الخطوة الأولى: تثبيت Redis
composer require predis/predis
# or
pecl install redis
الخطوة الثانية: إعداد ملف .env
CACHE_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
التخزين المؤقت الأساسي
use Illuminate\Support\Facades\Cache;
// Store value
Cache::put('key', 'value', now()->addMinutes(10));
// Get value
$value = Cache::get('key', 'default');
// Remember pattern (most common)
$users = Cache::remember('users', 3600, function () {
return User::all();
});
// Forever cache
Cache::forever('settings', $settings);
// Delete
Cache::forget('key');
وسوم التخزين المؤقت (Cache Tags)
// Store with tags
Cache::tags(['users', 'profiles'])->put('user.1', $user, 3600);
// Get with tags
$user = Cache::tags(['users', 'profiles'])->get('user.1');
// Flush by tag
Cache::tags(['users'])->flush();
نمط تخزين النماذج مؤقتاً
class Post extends Model
{
public static function getCached($id)
{
return Cache::tags(['posts'])->remember(
"post.{$id}",
3600,
fn() => static::with('author')->find($id)
);
}
protected static function booted()
{
static::saved(function ($post) {
Cache::tags(['posts'])->forget("post.{$post->id}");
});
static::deleted(function ($post) {
Cache::tags(['posts'])->forget("post.{$post->id}");
});
}
}
وسيط التخزين المؤقت (Cache Middleware)
// Cache entire response
Route::get('/posts', [PostController::class, 'index'])
->middleware('cache.headers:public;max_age=3600');
الأقفال الذرية (Atomic Locks)
$lock = Cache::lock('processing', 10);
if ($lock->get()) {
// Process...
$lock->release();
}
مراقبة التخزين المؤقت
# Check memory usage
redis-cli INFO memory
# Monitor commands
redis-cli MONITOR
التعليقات (0)
اترك تعليقًا
لا توجد تعليقات بعد. كن أول من يشارك أفكاره!