信息发布→ 登录 注册 退出

Laravel自定义缓存驱动?缓存扩展如何实现?

发布时间:2025-09-26

点击量:
首先创建实现Store接口的自定义缓存类,然后通过服务提供者用Cache::extend注册驱动,最后在config/cache.php中配置使用该驱动。

在Laravel中实现自定义缓存驱动,核心在于利用其强大的缓存管理器(Cache Manager)的扩展能力。这通常涉及编写一个服务提供者,并在其中注册一个新的缓存驱动器,该驱动器需要实现Illuminate\Contracts\Cache\Store接口,从而让Laravel知道如何与你的自定义缓存后端进行交互。说白了,就是告诉Laravel:“嘿,除了你认识的Redis、Memcached,我这儿还有个新的缓存地方,你按我说的去存取就行。”

解决方案

要实现一个Laravel自定义缓存驱动,我们大致需要分三步走:定义你的缓存存储逻辑、注册这个驱动、以及配置Laravel来使用它。

第一步:定义自定义缓存存储类

你需要创建一个类,它负责实际的缓存操作,比如数据的存、取、删除。这个类必须实现Illuminate\Contracts\Cache\Store接口。这个接口定义了所有缓存驱动需要实现的方法,比如getputforgetflush等。

我们以一个非常简化的文件系统缓存为例,但请注意,实际项目中你可能对接的是一个内部的KV存储、一个特定的数据库表,或者其他非标准后端。

path = $path;
        $this->prefix = $prefix;
        if (!is_dir($this->path)) {
            mkdir($this->path, 0777, true);
        }
    }

    /**
     * 获取缓存项的值。
     */
    public function get($key): mixed
    {
        $filePath = $this->getFilePath($key);
        if (!file_exists($filePath)) {
            return null;
        }

        $content = file_get_contents($filePath);
        $data = json_decode($content, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            // 文件内容损坏,或者不是有效的JSON
            $this->forget($key); // 清理掉损坏的缓存
            return null;
        }

        if (isset($data['expires']) && $data['expires'] !== null && Carbon::now()->timestamp > $data['expires']) {
            $this->forget($key); // 已过期
            return null;
        }

        return $data['value'] ?? null;
    }

    /**
     * 获取多个缓存项的值。
     */
    public function many(array $keys): array
    {
        $results = [];
        foreach ($keys as $key) {
            $results[$key] = $this->get($key);
        }
        return $results;
    }

    /**
     * 将数据存入缓存。
     *
     * @param string $key 缓存键
     * @param mixed $value 缓存值
     * @param int $minutes 缓存分钟数
     */
    public function put($key, $value, $minutes): bool
    {
        $filePath = $this->getFilePath($key);
        $expires = $minutes === 0 ? null : Carbon::now()->addMinutes($minutes)->timestamp;

        $data = json_encode([
            'value' => $value,
            'expires' => $expires,
        ]);

        return file_put_contents($filePath, $data) !== false;
    }

    /**
     * 将多个数据存入缓存。
     */
    public function putMany(array $values, $minutes): bool
    {
        $success = true;
        foreach ($values as $key => $value) {
            if (!$this->put($key, $value, $minutes)) {
                $success = false;
            }
        }
        return $success;
    }

    /**
     * 永久存储数据到缓存。
     */
    public function forever($key, $value): bool
    {
        return $this->put($key, $value, 0); // 0分钟表示永不过期
    }

    /**
     * 增加一个缓存项的值。
     *
     * 注意:对于文件缓存,这通常不是原子操作,在高并发下可能存在问题。
     */
    public function increment($key, $value = 1): int|bool
    {
        $current = (int) $this->get($key);
        $new = $current + $value;
        $this->put($key, $new, 0); // 重新存入,并保持永不过期或原有TTL
        return $new;
    }

    /**
     * 减少一个缓存项的值。
     */
    public function decrement($key, $value = 1): int|bool
    {
        $current = (int) $this->get($key);
        $new = $current - $value;
        $this->put($key, $new, 0);
        return $new;
    }

    /**
     * 从缓存中删除一个项。
     */
    public function forget($key): bool
    {
        $filePath = $this->getFilePath($key);
        if (file_exists($filePath)) {
            return unlink($filePath);
        }
        return true;
    }

    /**
     * 清空所有缓存。
     */
    public function flush(): bool
    {
        $files = glob($this->path . '/' . $this->prefix . '*.cache');
        foreach ($files as $file) {
            unlink($file);
        }
        return true;
    }

    /**
     * 获取缓存键的前缀。
     */
    public function getPrefix(): string
    {
        return $this->prefix;
    }

    /**
     * 获取缓存文件的完整路径。
     */
    protected function getFilePath(string $key): string
    {
        // 使用md5是为了避免文件名过长或包含特殊字符,同时保持唯一性
        return $this->path . '/' . $this->prefix . md5($key) . '.cache';
    }
}

第二步:注册自定义缓存驱动

我们需要创建一个服务提供者(Service Provider),在它的boot方法中,利用Cache::extend方法来注册我们的自定义驱动。

别忘了在config/app.php文件的providers数组中注册这个服务提供者:

    'providers' => [
        // ...
        App\Providers\CustomCacheServiceProvider::class,
    ],

第三步:配置Laravel使用自定义驱动

config/cache.php文件中,添加你的自定义驱动配置。

 
标签:# memcached  # 并在  # 我说  # 有个  # 在这里  # 的是  # 创建一个  # 管理器  # 多个  # 自定义  # 数据库  # laravel  # 接口  # 存储类  # red  # 后端  # app  # cad  # json  # js  # redis  # php  
在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!