laravel 10 支持通过实现 illuminate\contracts\cache\store 接口并注册自定义缓存驱动来扩展数据库缓存,需三步:一、创建继承 taggablestore 的类实现 get/put/forget 等方法;二、在服务提供者中用 cache::extend 注册驱动,并在 cache.php 配置 customdb 存储器;三、手动建表并自行处理过期清理。

Laravel 10 默认不提供数据库缓存的「自定义存储驱动」,但支持通过扩展 Cache\Store 实现任意后端(如 MongoDB、Berkeley DB、自建表结构等)。关键不是“改数据库驱动”,而是实现一个符合 Laravel 缓存契约的 Store 类,并注册进缓存系统。
下面直击核心,分三步讲清怎么做:
一、实现符合接口的自定义 Store 类
Laravel 缓存底层依赖 `Illuminate\Contracts\Cache\Store` 接口。你需要创建一个类(比如 `App\Cache\CustomDatabaseStore`),继承 `Illuminate\Cache\Repository` 的基类逻辑或直接实现该接口方法,重点覆盖: - get($key):根据 key 查数据库字段(如 `value`, `expiration`) - put($key, $value, $seconds):插入或更新带过期时间的记录(`expires_at = now() + $seconds`) - forget($key):按 key 删除 - flush():清空所有未过期项(可选加 `WHERE expires_at > NOW()`) - getMultiple($keys) 和 setMultiple($values, $seconds)(Laravel 10+ 推荐实现,提升批量性能)示例结构(简化):
namespace App\Cache;
use Illuminate\Cache\TaggableStore;
use Illuminate\Database\Connection;
class CustomDatabaseStore extends TaggableStore
{
protected $connection;
protected $table = 'cache_custom';
public function __construct(Connection $connection, string $table = 'cache_custom')
{
$this->connection = $connection;
$this->table = $table;
}
public function get($key)
{
$row = $this->connection->table($this->table)
->where('key', $key)
->where('expires_at', '>', now())
->first(['value']);
return $row ? unserialize($row->value) : null;
}
public function put($key, $value, $seconds)
{
$expiresAt = now()->addSeconds($seconds);
$this->connection->table($this->table)->upsert([
'key' => $key,
'value' => serialize($value),
'expires_at' => $expiresAt,
], ['key'], ['value', 'expires_at']);
}
// 其他方法依此类推...
}
二、注册为缓存 store 并配置到 cache.php
在服务提供者(如 `AppServiceProvider` 的 `boot()` 方法)中注册驱动:use Illuminate\Support\Facades\Cache;
use App\Cache\CustomDatabaseStore;
Cache::extend('customdb', function ($app) {
return Cache::repository(
new CustomDatabaseStore(
$app['db']->connection('mysql'), // 指定连接,可配多个
'my_cache_table'
)
);
});
然后在 config/cache.php 的 'stores' 中添加:
'customdb' => [
'driver' => 'customdb',
],
再把 'default' => 'customdb' 或通过 .env 设置 CACHE_DRIVER=customdb。











