"API'niz yavaş mı çalışıyor?" Laravel'in caching sistemini kullanarak API performansınızı 10 kat artırmanın profesyonel yöntemlerini öğrenelim!
API Caching, sık erişilen verilerin geçici olarak saklanmasıdır:
// Önbelleksiz $users = DB::table('users')->get(); // 120ms // Önbellekli $users = Cache::remember('users', 3600, function () { return DB::table('users')->get(); // İlk çağrı 120ms, sonrakiler 5ms! });
Route::get('/stats', function () { // 1 saat boyunca cache'de tut })->middleware('cache.headers:public;max_age=3600');
public function index() { return Cache::remember('posts.index', 60, function () { return Post::with('author')->paginate(20); }); }
class Post extends Model { protected static function booted() { static::updated(function ($post) { Cache::forget("posts.{$post->id}"); }); static::deleted(function ($post) { Cache::forget('posts.index'); Cache::forget("posts.{$post->id}"); }); } }
Cache::tags(['posts', 'authors'])->put($key, $value, $seconds); Cache::tags('posts')->flush(); // Sadece post cache'ini temizle
$etag = md5($users->toJson()); return response($users)->withHeaders([ 'ETag' => $etag, 'Cache-Control' => 'public, max-age=3600' ]);
$version = Cache::get('api_version', 1); $users = Cache::remember("users.v{$version}", 3600, function () { return User::all(); });
StoreHızKalıcılıkKarmaşıklıkKullanım AlanıRedis⚡⚡⚡⚡✅OrtaYüksek trafikli API'lerMemcached⚡⚡⚡⚡❌DüşükBasit cache ihtiyaçlarıDatabase⚡⚡✅YüksekNadir erişilen verilerFile⚡✅DüşükGeliştirme ortamı
class UserController extends Controller { public function show($id) { $user = Cache::remember("users.{$id}", 3600, function () use ($id) { return User::findOrFail($id); }); return new UserResource($user); } }
public function trending() { $throttleKey = 'trending:'.request()->ip(); return Cache::remember($throttleKey, 300, function () { return Post::trending()->limit(10)->get(); }); }
// Çoklu cache okuma $keys = ['users.stats', 'posts.latest', 'comments.count']; $cachedData = Cache::many($keys); // Atomic lock ile cache stampede önleme $value = Cache::lock('expensive_data')->block(5, function () { return expensiveCalculation(); });
Doğru caching ile:
API'nizde hangi caching stratejilerini kullanıyorsunuz? Yorumlarda paylaşın! 💬
Bir sonraki yazımız: 🚀 [Laravel'de API Authentication: Token ve OAuth Kullanımı] - API'nizi güvenceye alın!
#Laravel #API #Caching #Performance #WebDevelopment 🏎️