Skip to content

多级缓存 ​

概述 ​

多级缓存是一种使用多层级存储介质的缓存架构,通过在各级缓存之间合理分配数据,实现性能和成本的最优平衡。Kuiper 框架通过 Composite 驱动实现了灵活的多级缓存支持。

多级缓存架构 ​

三级缓存架构 ​

text
┌─────────────────────────────────────────────────────────────┐
│                        应用层                                │
├─────────────────────────────────────────────────────────────┤
│                        L1 缓存                                │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  Ephemeral (内存缓存)                                 │   │
│  │  - 容量: 1000 项                                      │   │
│  │  - TTL: 60 秒                                         │   │
│  │  - 速度: 极快                                         │   │
│  └─────────────────────────────────────────────────────┘   │
├─────────────────────────────────────────────────────────────┤
│                        L2 缓存                                │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  FileDriver (文件缓存)                                │   │
│  │  - 容量: 无限制                                       │   │
│  │  - TTL: 3600 秒                                       │   │
│  │  - 速度: 中等                                         │   │
│  └─────────────────────────────────────────────────────┘   │
├─────────────────────────────────────────────────────────────┤
│                        L3 缓存                                │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  RedisDriver (Redis 缓存)                             │   │
│  │  - 容量: 受 Redis 内存限制                             │   │
│  │  - TTL: 86400 秒                                      │   │
│  │  - 速度: 极快                                         │   │
│  │  - 分布式: 支持                                        │   │
│  └─────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────┘

图中 TTL 仅为示意

Composite 写入时会把同一个过期时间写给所有驱动,因此 L2/L3 没有独立的 TTL 配置;只有 Ephemeral 的 max_lifetime 能为 L1 设置存活时间上限(max_lifetime > 0 才生效,截断规则是 min(条目过期时间, now + max_lifetime),没有任何倍数换算;FileDriver 不消费 ttl 选项,该选项会被静默忽略)。实际条目 TTL 由 application.cache.lifetime 或 $item->expiresAfter() 决定。详见缓存配置。

读取流程 ​

text
1. 应用请求缓存数据
   │
2. 查询 L1 缓存(内存)
   │
   ├─ 命中 ──> 返回数据
   │
   └─ 未命中 ──> 查询 L2 缓存(文件)
       │
       ├─ 命中 ──> 同步到 L1 ──> 返回数据
       │
       └─ 未命中 ──> 查询 L3 缓存(Redis)
           │
           ├─ 命中 ──> 同步到 L2、L1 ──> 返回数据
           │
           └─ 未命中 ──> 返回 null

写入流程 ​

text
1. 应用写入缓存数据
   │
2. 写入 L3 缓存(Redis)
   │
3. 写入 L2 缓存(文件)
   │
4. 写入 L1 缓存(内存)
   │
5. 返回成功

ChainedCache 实现 ​

Kuiper 框架提供了 ChainedCache 类实现链式缓存,支持 PSR-16 接口。

基本使用 ​

php
<?php

declare(strict_types=1);

use kuiper\cache\ArrayCache;
use kuiper\cache\ChainedCache;
use kuiper\cache\stash\CacheItemPool;
use kuiper\cache\stash\driver\Ephemeral;
use kuiper\cache\stash\driver\FileDriver;
use kuiper\cache\stash\driver\RedisDriver;

// 创建各级缓存(ChainedCache 接收 PSR-16 CacheInterface 列表)
$l1Cache = new ArrayCache(60, 1000);   // L1: 内存缓存
$l2Cache = new ArrayCache(3600);       // L2: 第二级缓存(这里同样用 ArrayCache 演示)

// 组合缓存
$chainedCache = new ChainedCache([
    $l1Cache,  // L1 缓存
    $l2Cache,  // L2 缓存
]);

// 使用链式缓存
$chainedCache->set('user:123', $userData, 7200);
$user = $chainedCache->get('user:123');

语义要点 ​

  • 写穿所有层:set() / setMultiple() 对每一层都执行写入;任一层写 失败整体返回 false(失败会暴露,不静默吞掉)。
  • 读回退:按层顺序逐层读取,命中即返回;全部 miss 返回 $default (用哨兵对象区分「命中且值等于 default」与 miss,不会多查一次底层)。
  • 删除与清空:delete() / deleteMultiple() 对每一层精确删除, clear() 清空每一层;任一层失败整体返回 false。
  • 键校验:所有方法都要求键至少包含一个非空分段('/' 分隔), 非法键(''、'/'、'//')抛 InvalidArgumentException。
  • 本地失效:实现 LocalInvalidationInterface 的层(ArrayCache、 内嵌的 ChainedCache)会响应 invalidateLocal() / clearLocal(), 用于跨进程失效广播(见跨进程一致性)。

使用 Composite 驱动 ​

php
<?php

declare(strict_types=1);

use kuiper\cache\stash\CacheItemPool;
use kuiper\cache\stash\driver\Composite;
use kuiper\cache\stash\driver\Ephemeral;
use kuiper\cache\stash\driver\FileDriver;
use kuiper\cache\stash\driver\RedisDriver;

// 创建各级驱动
$l1Driver = new Ephemeral([
    'max_items' => 1000,
    'max_lifetime' => 60,  // L1 条目最大存活时间上限(Ephemeral 合法选项)
]);

$l2Driver = new FileDriver([
    'dir' => '/tmp/cache',
    // 注意:FileDriver 没有生效的 ttl 选项
]);

$l3Driver = new RedisDriver([
    'redis' => $redis,
    'prefix' => 'myapp:',
]);

// 组合驱动
$composite = new Composite([
    'drivers' => [$l1Driver, $l2Driver, $l3Driver],
]);

// 创建缓存池(默认 TTL 同时作用于所有级别,L1 还受 max_lifetime 上限约束)
$pool = new CacheItemPool($composite);
$pool->setDefaultTtl(7200);

// 使用缓存池
$item = $pool->getItem('user:123');
if (!$item->isHit()) {
    $user = fetchUserFromDatabase(123);
    $item->set($user);
    $item->expiresAfter(7200);
    $pool->save($item);  // 自动写入所有级别
}

$user = $item->get();  // 返回刚写入的值(条目内存值;未写入时才会读驱动)

set() 不会把条目变成「命中」

CacheItem::set() 只更新内存值,不改写 isHit()(与 symfony/cache 一致): 命中状态只反映驱动里的内容。因此 set() 之后 isHit() 仍为 false, 但 get() 会返回刚设置的值。要判断「驱动里有没有」必须重新 getItem() 或用 hasItem()。

缓存穿透 ​

缓存穿透是指查询一个不存在的数据,由于缓存没有命中,每次请求都会穿透到数据库。

解决方案 ​

1. 缓存空值 ​

php
<?php

declare(strict_types=1);

use Psr\Cache\CacheItemPoolInterface;

class UserService
{
    public function __construct(
        private readonly CacheItemPoolInterface $cache,
        private readonly \PDO $db
    ) {
    }

    public function find(int $id): ?array
    {
        $item = $this->cache->getItem("user:{$id}");

        if (!$item->isHit()) {
            $stmt = $this->db->prepare('SELECT * FROM users WHERE id = ?');
            $stmt->execute([$id]);
            $user = $stmt->fetch(\PDO::FETCH_ASSOC);

            // 缓存空值,避免穿透
            if ($user === false) {
                $item->set(null);
                $item->expiresAfter(60); // 空值短期缓存
            } else {
                $item->set($user);
                $item->expiresAfter(3600);
            }

            $this->cache->save($item);
        }

        return $item->get();
    }
}

2. 布隆过滤器 ​

php
<?php

declare(strict_types=1);

use Bloom\BloomFilter;

class UserServiceWithBloomFilter
{
    public function __construct(
        private readonly CacheItemPoolInterface $cache,
        private readonly \PDO $db,
        private readonly BloomFilter $bloomFilter
    ) {
    }

    public function find(int $id): ?array
    {
        // 先检查布隆过滤器
        if (!$this->bloomFilter->has($id)) {
            // 布隆过滤器判断不存在,直接返回
            return null;
        }

        $item = $this->cache->getItem("user:{$id}");

        if (!$item->isHit()) {
            $user = $this->fetchFromDatabase($id);
            $item->set($user);
            $item->expiresAfter(3600);
            $this->cache->save($item);

            // 添加到布隆过滤器
            if ($user !== null) {
                $this->bloomFilter->add($id);
            }
        }

        return $item->get();
    }
}

缓存击穿 ​

缓存击穿是指某个热点数据过期时,大量请求同时查询数据库。

解决方案 ​

1. 互斥锁 ​

php
<?php

declare(strict_types=1);

use Psr\Cache\CacheItemPoolInterface;

class UserServiceWithLock
{
    public function __construct(
        private readonly CacheItemPoolInterface $cache,
        private readonly \PDO $db,
        private readonly \Redis $redis
    ) {
    }

    public function find(int $id): ?array
    {
        $item = $this->cache->getItem("user:{$id}");

        if (!$item->isHit()) {
            // 获取互斥锁
            $lockKey = "lock:user:{$id}";
            $lock = $this->redis->set($lockKey, 1, ['nx', 'ex' => 10]);

            if ($lock) {
                // 获取锁成功,从数据库加载
                try {
                    $user = $this->fetchFromDatabase($id);
                    $item->set($user);
                    $item->expiresAfter(3600);
                    $this->cache->save($item);
                } finally {
                    // 释放锁
                    $this->redis->del($lockKey);
                }
            } else {
                // 获取锁失败,等待后重试
                usleep(100000); // 等待 100ms
                return $this->find($id); // 重试
            }
        }

        return $item->get();
    }
}

2. 单飞(框架内置) ​

框架内置 SingleFlightCache(SETNX 占位 + 双检 + 等待重读),热点 key 过期瞬间的并发回源只发生一次;占位锁自带 TTL,持锁进程崩溃后自动过期:

php
<?php

declare(strict_types=1);

use kuiper\cache\singleflight\SingleFlightCache;

$sf = new SingleFlightCache($this->cache, $this->redis);
$value = $sf->getOrCreate("user:{$id}", fn () => $this->fetchFromDatabase($id), ttl: 3600);

细节见跨进程一致性。

3. 热点数据永不过期 ​

php
<?php

declare(strict_types=1);

use Psr\Cache\CacheItemPoolInterface;

class UserServiceWithHotData
{
    public function __construct(
        private readonly CacheItemPoolInterface $cache,
        private readonly \PDO $db
    ) {
    }

    public function find(int $id): ?array
    {
        $item = $this->cache->getItem("user:{$id}");

        if (!$item->isHit()) {
            $user = $this->fetchFromDatabase($id);

            // 热点数据设置较长的过期时间
            $item->set($user);
            $item->expiresAfter(86400); // 24 小时
            $this->cache->save($item);
        }

        // 检查是否需要异步刷新
        $this->checkAndRefresh($id);

        return $item->get();
    }

    private function checkAndRefresh(int $id): void
    {
        $refreshItem = $this->cache->getItem("refresh:user:{$id}");

        if (!$refreshItem->isHit()) {
            // 异步刷新缓存
            $this->asyncRefresh($id);

            $refreshItem->set(true);
            $refreshItem->expiresAfter(300); // 5 分钟内不重复刷新
            $this->cache->save($refreshItem);
        }
    }

    private function asyncRefresh(int $id): void
    {
        // 异步刷新逻辑
        // 可以使用队列、协程等实现
    }
}

缓存雪崩 ​

缓存雪崩是指大量缓存同时失效,导致大量请求直接访问数据库。

解决方案 ​

1. 随机过期时间 ​

php
<?php

declare(strict_types=1);

use Psr\Cache\CacheItemPoolInterface;

class UserServiceWithRandomTTL
{
    public function __construct(
        private readonly CacheItemPoolInterface $cache,
        private readonly \PDO $db
    ) {
    }

    public function find(int $id): ?array
    {
        $item = $this->cache->getItem("user:{$id}");

        if (!$item->isHit()) {
            $user = $this->fetchFromDatabase($id);
            $item->set($user);

            // 添加随机偏移,避免同时失效
            $ttl = 3600 + rand(0, 300); // 3600-3900 秒
            $item->expiresAfter($ttl);
            $this->cache->save($item);
        }

        return $item->get();
    }
}

2. 多级缓存 ​

多级缓存本身就是防止雪崩的有效方案:

php
<?php

declare(strict_types=1);

use kuiper\cache\stash\CacheItemPool;
use kuiper\cache\stash\driver\Composite;
use kuiper\cache\stash\driver\Ephemeral;
use kuiper\cache\stash\driver\FileDriver;
use kuiper\cache\stash\driver\RedisDriver;

// L1 用 max_lifetime 设置存活时间上限;L2/L3 共享条目 TTL(无法按级别单独设置)
$l1Driver = new Ephemeral([
    'max_items' => 1000,
    'max_lifetime' => 60,  // L1: 条目最长存活 60 秒
]);

$l2Driver = new FileDriver([
    'dir' => '/tmp/cache',
]);

$l3Driver = new RedisDriver([
    'redis' => $redis,
    'prefix' => 'myapp:',
]);

$composite = new Composite([
    'drivers' => [$l1Driver, $l2Driver, $l3Driver],
]);

$pool = new CacheItemPool($composite);
$pool->setDefaultTtl(3600); // L2/L3 的条目 TTL

// 即使 L3 缓存雪崩,L1/L2 仍能提供缓存

3. 缓存预热 ​

php
<?php

declare(strict_types=1);

use kuiper\di\attribute\Bean;
use kuiper\di\attribute\Configuration;
use Psr\Cache\CacheItemPoolInterface;

#[Configuration]
class CacheWarmupConfiguration
{
    #[Bean]
    public function cacheWarmer(CacheItemPoolInterface $cache): void
    {
        // 应用启动时预热缓存
        $this->warmupUserCache($cache);
        $this->warmupConfigCache($cache);
        $this->warmupProductCache($cache);
    }

    private function warmupUserCache(CacheItemPoolInterface $cache): void
    {
        // 预加载热点用户数据
        $hotUserIds = [1, 2, 3, 100, 200];

        foreach ($hotUserIds as $id) {
            $item = $cache->getItem("user:{$id}");
            if (!$item->isHit()) {
                $user = $this->fetchUserFromDatabase($id);
                $item->set($user);

                // 分散过期时间
                $ttl = 3600 + ($id % 300);
                $item->expiresAfter($ttl);
                $cache->save($item);
            }
        }
    }

    private function warmupConfigCache(CacheItemPoolInterface $cache): void
    {
        // 预加载配置数据
        $configs = ['database', 'redis', 'cache'];

        foreach ($configs as $name) {
            $item = $cache->getItem("config:{$name}");
            if (!$item->isHit()) {
                $config = $this->loadConfig($name);
                $item->set($config);
                $item->expiresAfter(86400); // 配置缓存 24 小时
                $cache->save($item);
            }
        }
    }
}

缓存更新策略 ​

Cache-Aside(旁路缓存) ​

php
<?php

declare(strict_types=1);

use Psr\Cache\CacheItemPoolInterface;

class CacheAsideService
{
    public function __construct(
        private readonly CacheItemPoolInterface $cache,
        private readonly \PDO $db
    ) {
    }

    public function get(string $key): mixed
    {
        // 1. 先查缓存
        $item = $this->cache->getItem($key);

        if ($item->isHit()) {
            return $item->get();
        }

        // 2. 缓存未命中,查数据库
        $value = $this->fetchFromDatabase($key);

        // 3. 写入缓存
        $item->set($value);
        $item->expiresAfter(3600);
        $this->cache->save($item);

        return $value;
    }

    public function update(string $key, mixed $value): void
    {
        // 1. 更新数据库
        $this->updateDatabase($key, $value);

        // 2. 删除缓存
        $this->cache->deleteItem($key);
    }
}

Write-Through(直写) ​

php
<?php

declare(strict_types=1);

use Psr\Cache\CacheItemPoolInterface;

class WriteThroughService
{
    public function __construct(
        private readonly CacheItemPoolInterface $cache,
        private readonly \PDO $db
    ) {
    }

    public function update(string $key, mixed $value): void
    {
        // 1. 同时更新缓存和数据库
        $item = $this->cache->getItem($key);
        $item->set($value);
        $item->expiresAfter(3600);
        $this->cache->save($item);

        $this->updateDatabase($key, $value);
    }

    public function get(string $key): mixed
    {
        // 直接从缓存读取
        $item = $this->cache->getItem($key);

        if (!$item->isHit()) {
            throw new \RuntimeException("数据未缓存");
        }

        return $item->get();
    }
}

Write-Behind(回写) ​

php
<?php

declare(strict_types=1);

use Psr\Cache\CacheItemPoolInterface;

class WriteBehindService
{
    private array $pendingWrites = [];

    public function __construct(
        private readonly CacheItemPoolInterface $cache,
        private readonly \PDO $db
    ) {
    }

    public function update(string $key, mixed $value): void
    {
        // 1. 立即更新缓存
        $item = $this->cache->getItem($key);
        $item->set($value);
        $item->expiresAfter(3600);
        $this->cache->save($item);

        // 2. 加入待写队列
        $this->pendingWrites[$key] = $value;
    }

    public function flush(): void
    {
        // 批量写入数据库
        foreach ($this->pendingWrites as $key => $value) {
            $this->updateDatabase($key, $value);
        }

        $this->pendingWrites = [];
    }
}

缓存监控 ​

缓存命中率监控 ​

php
<?php

declare(strict_types=1);

use Psr\Cache\CacheItemPoolInterface;

class CacheMonitor
{
    private int $hits = 0;
    private int $misses = 0;
    private array $stats = [];

    public function __construct(
        private readonly CacheItemPoolInterface $cache
    ) {
    }

    public function get(string $key): mixed
    {
        $item = $this->cache->getItem($key);

        if ($item->isHit()) {
            ++$this->hits;
            $this->recordStats($key, true);
            return $item->get();
        }

        ++$this->misses;
        $this->recordStats($key, false);
        return null;
    }

    public function getHitRate(): float
    {
        $total = $this->hits + $this->misses;
        return $total > 0 ? $this->hits / $total : 0;
    }

    public function getStats(): array
    {
        return [
            'hits' => $this->hits,
            'misses' => $this->misses,
            'hit_rate' => $this->getHitRate(),
            'key_stats' => $this->stats,
        ];
    }

    private function recordStats(string $key, bool $hit): void
    {
        $prefix = explode(':', $key)[0] ?? 'unknown';

        if (!isset($this->stats[$prefix])) {
            $this->stats[$prefix] = ['hits' => 0, 'misses' => 0];
        }

        if ($hit) {
            ++$this->stats[$prefix]['hits'];
        } else {
            ++$this->stats[$prefix]['misses'];
        }
    }
}

最佳实践 ​

  1. 合理设置 TTL:L1 用 Ephemeral 的 max_lifetime 设存活上限,L2/L3 共享 条目 TTL(Composite 把同一个过期时间写给所有层,无法按层分别设置)
  2. 使用随机 TTL:避免同时失效
  3. 缓存空值:防止缓存穿透
  4. 使用互斥锁:防止缓存击穿
  5. 多级缓存:防止缓存雪崩
  6. 监控缓存命中率:优化缓存策略
  7. 定期清理缓存:避免内存溢出
  8. 异步刷新热点数据:保持数据新鲜度

下一步 ​

基于 MIT 许可发布