Giao diện
Cache
Giới thiệu (Introduction)
Một số tác vụ lấy hoặc xử lý dữ liệu có thể tốn CPU hoặc mất vài giây để hoàn thành. Khi đó, cache dữ liệu để truy xuất nhanh hơn cho các request tiếp theo là cách tiếp cận phổ biến. Laravel cung cấp API thống nhất cho nhiều cache backends.
Cấu hình (Configuration)
File cấu hình tại config/cache.php. Laravel hỗ trợ các cache backends phổ biến:
| Driver | Mô tả |
|---|---|
database | Lưu cache trong database (mặc định) |
file | Lưu cache trong filesystem |
memcached | Sử dụng Memcached server |
redis | Sử dụng Redis server |
dynamodb | Sử dụng AWS DynamoDB |
array | Lưu trong array (cho testing) |
null | Không cache (cho testing) |
Driver Prerequisites
Database
Mặc định driver database đã được cấu hình sẵn.
Redis
Cài package predis/predis hoặc extension phpredis:
bash
composer require predis/predisSử dụng Cache (Cache Usage)
Lấy Cache Instance
php
use Illuminate\Support\Facades\Cache;
$value = Cache::get('key');
// Store cụ thể
$value = Cache::store('redis')->get('key');Lấy Items từ Cache
php
$value = Cache::get('key');
$value = Cache::get('key', 'default');
// Closure làm default
$value = Cache::get('key', function () {
return DB::table('users')->get();
});Kiểm tra Item tồn tại
php
if (Cache::has('key')) {
// ...
}Tăng / Giảm giá trị
php
Cache::add('key', 0, now()->plus(hours: 4));
Cache::increment('key');
Cache::increment('key', $amount);
Cache::decrement('key');
Cache::decrement('key', $amount);Lấy và Lưu (Retrieve & Store)
php
$value = Cache::remember('users', $seconds, function () {
return DB::table('users')->get();
});
// Cache vĩnh viễn
$value = Cache::rememberForever('users', function () {
return DB::table('users')->get();
});Lấy và Xóa (Retrieve & Delete)
php
$value = Cache::pull('key');Lưu Items vào Cache
php
Cache::put('key', 'value', $seconds);
Cache::put('key', 'value', now()->addMinutes(10));
// Lưu vĩnh viễn
Cache::forever('key', 'value');
// Chỉ store nếu chưa có
Cache::add('key', 'value', $seconds);Xóa Items
php
Cache::forget('key');
// Đặt TTL = 0 hoặc âm
Cache::put('key', 'value', 0);
Cache::put('key', 'value', -5);
// Xóa toàn bộ
Cache::flush();Cache Memoization
Cache::memo() — lưu cache trong process memory, giảm truy cập backend:
php
$value = Cache::memo('key');
$value = Cache::memo()->get('key');Cache Helper
php
// Lấy
$value = cache('key');
// Lưu
cache(['key' => 'value'], $seconds);
cache(['key' => 'value'], now()->addMinutes(10));Cache Tags
LƯU Ý
Cache tags không hỗ trợ với drivers file, dynamodb, hoặc database.
Lưu Tagged Items
php
Cache::tags(['people', 'artists'])->put('John', $john, $seconds);
Cache::tags(['people', 'authors'])->put('Anne', $anne, $seconds);Truy cập Tagged Items
php
$john = Cache::tags(['people', 'artists'])->get('John');
$anne = Cache::tags(['people', 'authors'])->get('Anne');Xóa Tagged Items
php
Cache::tags(['people', 'authors'])->flush();
Cache::tags('authors')->flush();Atomic Locks
GHI CHÚ
Atomic Locks yêu cầu drivers hỗ trợ atomic operations: memcached, redis, dynamodb, database, file, hoặc array.
Quản lý Locks
php
$lock = Cache::lock('foo', 10); // Lock 10 giây
if ($lock->get()) {
// Lock acquired, xử lý...
$lock->release();
}
// Block chờ đến khi lock khả dụng
Cache::lock('foo', 10)->block(5, function () {
// Chờ tối đa 5 giây để acquire lock...
});Concurrency Limiting
Giới hạn đồng thời bằng lock:
php
use Illuminate\Support\Facades\Cache;
use Illuminate\Contracts\Cache\LockTimeoutException;
try {
Cache::lock('processing')->block(10, function () {
// Xử lý đồng thời bị giới hạn...
});
} catch (LockTimeoutException $e) {
// Không thể acquire lock...
}Cache Failover
Cấu hình fallback stores khi primary store không khả dụng:
php
'redis' => [
'driver' => 'redis',
'connection' => 'cache',
'failover' => 'database',
],Thêm Custom Cache Drivers
Viết Driver
Implement Illuminate\Contracts\Cache\Store:
php
<?php
namespace App\Extensions;
use Illuminate\Contracts\Cache\Store;
class MongoStore implements Store
{
public function get($key) {}
public function many(array $keys) {}
public function put($key, $value, $seconds) {}
public function putMany(array $values, $seconds) {}
public function increment($key, $value = 1) {}
public function decrement($key, $value = 1) {}
public function forever($key, $value) {}
public function forget($key) {}
public function flush() {}
public function getPrefix() {}
}Đăng ký Driver
php
Cache::extend('mongo', function (Application $app) {
return Cache::repository(new MongoStore);
});Events
Cache dispatch events khi thao tác — hữu ích cho monitoring:
| Event | Mô tả |
|---|---|
CacheHit | Khi get thành công |
CacheMissed | Khi get không tìm thấy |
KeyWritten | Khi item được lưu |
KeyForgotten | Khi item bị xóa |