缓存驱动
概述
Kuiper 缓存模块提供了多种缓存驱动,支持不同的存储介质和场景。每种驱动都有其特性和适用场景,开发者可以根据实际需求选择合适的驱动。
驱动接口
所有缓存驱动都实现 DriverInterface 接口:
<?php
declare(strict_types=1);
namespace kuiper\cache\stash\driver;
interface DriverInterface
{
/**
* 获取缓存数据
*
* @param string $key 缓存键
* @return array 包含 'data' 和 'expiration' 的数组
*/
public function getData(string $key): array;
/**
* 存储缓存数据
*
* @param string $key 缓存键
* @param mixed $data 缓存数据
* @param int $expiration 过期时间戳
* @return bool 是否成功
*/
public function storeData(string $key, mixed $data, int $expiration): bool;
/**
* 精确删除单个键(不做键树/前缀级联)
*
* 与 clear() 的区别:clear($key) 是「键树」语义(删除该键及其
* '/' 分隔的子键),delete() 只删除 key 本身,供
* CacheItemPool::deleteItem() 使用。
*
* @param string $key 缓存键
* @return bool 删除是否成功(键不存在视为成功)
*/
public function delete(string $key): bool;
/**
* 清除缓存
*
* @param string|null $key 缓存键,null 表示清空所有
* @return bool 是否成功
*/
public function clear(?string $key = null): bool;
/**
* 清理过期缓存
*
* @return bool 是否成功
*/
public function purge(): bool;
}delete() 与 clear($key) 的区别
delete($key) 只删这一个键;clear($key) 按「键树」语义删该键及其 '/' 分隔的子键(clear('a') 会连带删除 a/b,但不会删除 ab—— 裸前缀匹配会误删同前缀的兄弟键)。PSR-6 的 CacheItemPool::deleteItem() 走的是 delete()(精确删除),池级的 clear() 则整池清空。 继承 AbstractDriver 的自定义驱动不实现 delete() 也能工作:基类 降级为 clear($key) 的键树语义兜底。
损坏条目的统一语义(三驱动一致)
RedisDriver、FileDriver、Ephemeral 三个驱动共用同一个 kuiper\cache\stash\IncompleteClassDetector,对「反序列化产物不可用」的条目 处理语义完全一致:
- 嵌套检测:不仅检查反序列化结果本身,还递归检查数组元素与任意对象的 属性(含
protected/private,深度上限 8)。此前只检查顶层,会漏掉 「白名单内的对象里嵌套着白名单外的对象」——业务代码拿到属性全是 PHP warning +null的哑对象,既不像命中也不像未命中。 __PHP_Incomplete_Class按 miss 处理:allowed_classes白名单外 (或缺省false)的类反序列化成__PHP_Incomplete_Class(含嵌套在数组 或对象属性里的实例)。检测到即按未命中返回并删除损坏条目——留着只会 每次读取都重复触发。- 告警通道随驱动而异:
RedisDriver注入 logger 时记录 warning (提示配置allowed_classes白名单);FileDriver与Ephemeral没有 logger 依赖,静默按 miss 处理。
FileDriver 读路径的额外保证:反序列化抛出的任何 \Throwable(含对象 __wakeup() 抛的异常)与 unserialize 返回 false 都按 miss 处理并删除 损坏的缓存文件,异常不会穿透到业务代码打挂请求。
ArrayCache
ArrayCache 是一个简单的内存缓存实现,基于 PHP 数组存储数据。
特性
- 存储介质:PHP 数组
- 生命周期:进程级,进程结束数据丢失
- 序列化:无——直接存 PHP 值(对象可原样存取,不需要反序列化白名单)
- 容量限制:支持最大容量配置
- 本地失效:实现
LocalInvalidationInterface,跨进程失效广播时只清理本进程 - 适用场景:单进程应用、测试环境
配置参数
<?php
use kuiper\cache\ArrayCache;
$cache = new ArrayCache(
ttl: 60, // 默认 TTL(秒)
capacity: 256, // 最大缓存项数
fillRate: 0.6, // 清理后保留比例
timeFactory: 'time' // 时间函数
);使用示例
<?php
declare(strict_types=1);
use kuiper\cache\ArrayCache;
$cache = new ArrayCache(
ttl: 300,
capacity: 1000
);
// 设置缓存
$cache->set('user:123', ['name' => 'John'], 600);
// 获取缓存
$user = $cache->get('user:123');
// 批量操作
$cache->setMultiple([
'user:1' => ['name' => 'Alice'],
'user:2' => ['name' => 'Bob'],
]);
// 检查缓存是否存在
if ($cache->has('user:123')) {
echo "缓存存在\n";
}
// 删除缓存
$cache->delete('user:123');性能特点
| 指标 | 值 | 说明 |
|---|---|---|
| 读取速度 | 极快 | 内存直接访问 |
| 写入速度 | 极快 | 内存直接写入 |
| 持久化 | 无 | 进程结束数据丢失 |
| 并发安全 | 否 | 需要外部同步 |
| 容量限制 | 有 | 受内存限制 |
Ephemeral
Ephemeral 是一个增强的内存缓存驱动,支持自动过期清理和序列化。
特性
- 存储介质:PHP 数组
- 自动过期:自动清理过期缓存
- 序列化支持:可选序列化存储
- 最大生命周期:可设置最大生命周期
- 容量管理:自动清理超过容量的缓存
配置参数
<?php
use kuiper\cache\stash\driver\Ephemeral;
$driver = new Ephemeral([
'max_items' => 1000, // 最大缓存项数(默认 256,0 表示不限制)
'serialize' => true, // 是否序列化存储(默认 true)
'fill_rate' => 0.6, // 触顶收缩时保留比例
'max_lifetime' => 7200, // 条目最大生命周期(秒),0 表示不截断
'allowed_classes' => true, // 反序列化白名单(true/false 或类名数组,支持 'App\Dto\*' 通配)
'time_factory' => 'time', // 时间函数
]);驱动选项键名统一 snake_case
Ephemeral 与 RedisDriver 的选项键名统一为 snake_case(max_items、 serialize、fill_rate、max_lifetime、allowed_classes;RedisDriver 的 allowed_classes、index_cache_ttl 不变)。v0.9 早期的 camelCase 键名 (maxItems 等)保留为兼容别名:仍然生效,但触发 E_USER_DEPRECATED 提示 迁移;同名的两种写法同时出现时以 snake_case 为准。
未知选项在装配期显式抛 InvalidArgumentException(与 swoole 包的 PoolConfig 一致)——拼错的键名不会被静默忽略。
serialized 曾经是合法选项,v0.9.4 起被移除
serialized 在 v0.9.3 是 Ephemeral 的合法首选键(serialize 只是它的 兼容别名)。v0.9.4 起选项键统一为 snake_case 白名单 (max_items / serialize / fill_rate / max_lifetime / time_factory / allowed_classes),serialized 不在其中,会直接失败:
InvalidArgumentException: Unknown Ephemeral option: "serialized"存量配置请把 serialized 改成 serialize(语义一致)。 lifetime、capacity、ttl 则从来不是合法选项。
合法选项的用法:
- 要限制 L1 条目的最大存活时间,用
max_lifetime(max_lifetime > 0才生效, 截断规则是expiration = min(expiration, now + max_lifetime),没有任何倍数换算); - 通过框架配置
application.cache.memory.lifetime间接设置时,CacheConfiguration在lifetime > 0时把它原样作为max_lifetime(无倍数换算),lifetime = 0(默认)表示不截断; Ephemeral的默认白名单是true(放行一切类,与 symfony/cache 策略一致)——false(最严,禁止一切类)只用于显式收紧的场景。 :::
使用示例
<?php
declare(strict_types=1);
use kuiper\cache\stash\CacheItemPool;
use kuiper\cache\stash\driver\Ephemeral;
$driver = new Ephemeral([
'max_items' => 10000,
'serialize' => true,
'max_lifetime' => 3600,
]);
$pool = new CacheItemPool($driver);
// 使用缓存池
$item = $pool->getItem('config:database');
if (!$item->isHit()) {
$config = loadDatabaseConfig();
$item->set($config);
$item->expiresAfter(1800);
$pool->save($item);
}
$config = $item->get();容量管理
Ephemeral 驱动使用以下策略管理容量:
- 清理过期项:容量触顶时首先清理所有过期的缓存项
- 写入后收缩:写入导致条目数超过容量时,按
fill_rate保留最新的条目 (批量收缩摊销淘汰成本);条目数始终不超过max_items
<?php
// 容量管理配置
$driver = new Ephemeral([
'max_items' => 1000, // 最大 1000 项
'fill_rate' => 0.6, // 触顶收缩后保留 60%
]);
// 当缓存项达到 1000 时:
// 1. 先清理所有过期项腾位
// 2. 写入后仍超过 1000 时,收缩到保留最新的 600 项(1000 * 0.6)
// 3. 条目数不会超过 max_items(触顶不会多存 1 条)性能特点
| 指标 | 值 | 说明 |
|---|---|---|
| 读取速度 | 极快 | 内存直接访问 |
| 写入速度 | 快 | 包含序列化开销 |
| 持久化 | 无 | 进程结束数据丢失 |
| 自动清理 | 是 | 自动清理过期项 |
| 容量限制 | 有 | 配置可控 |
FileDriver
FileDriver 使用文件系统存储缓存数据,支持跨进程共享和持久化。
特性
- 存储介质:文件系统
- 持久化:支持持久化存储
- 跨进程共享:支持多进程共享缓存
- Swoole 集成:协程安全的文件操作
- 版本控制:支持缓存文件版本管理
- 目录安全:构造时校验缓存目录属主并拒绝软链目录
- 反序列化白名单:
allowed_classes可在多租户/共享目录场景收紧 - 损坏容错:反序列化抛异常(含
__wakeup()抛的\Throwable)、返回false、检测到__PHP_Incomplete_Class(含嵌套实例)均按 miss 处理并 删除损坏文件,异常不穿透到业务代码(见 统一语义)
配置参数
<?php
use kuiper\cache\stash\driver\FileDriver;
$driver = new FileDriver([
'dir' => '/tmp/cache', // 缓存目录(默认 {tmp}/kuiper-cache-{uid},按 uid 隔离)
'allowed_classes' => true, // 反序列化白名单:true / false / 类名数组
//(元素可为精确类名或 'App\Dto\*' 通配前缀)
]);ttl 选项不被消费
FileDriver 不再读取 ttl 选项(该选项此前只被保存、从未消费,现在连保存都 没有了),传入会被静默忽略。缓存条目的过期时间由 CacheItemPool 的默认 TTL(默认 300 秒,可用 application.cache.lifetime 调整)以及 $item->expiresAfter() 决定。
目录安全(属主校验 + 软链拒绝)
共享临时目录(/tmp)上的同名目录可被他人抢先创建(sticky 位只保护删除, 不保护创建),缓存文件被替换后,读取侧会 unserialize 他人写入的载荷—— PHP 对象注入。因此 FileDriver 在构造时(校验口径与 swoole 包的 ConnectionProxyGenerator 一致):
- 目录已存在时同样校验属主:不是当前进程用户的目录直接抛
RuntimeException,不再继续使用; - 拒绝软链目录(
is_link,含断链软链); - 目录权限收紧到
0700(缓存文件0600)。
自定义 dir 时请指向应用私有的、当前用户拥有的目录。
使用示例
<?php
declare(strict_types=1);
use kuiper\cache\stash\CacheItemPool;
use kuiper\cache\stash\driver\FileDriver;
$driver = new FileDriver([
'dir' => __DIR__.'/../cache',
]);
$pool = new CacheItemPool($driver);
// 使用缓存
$item = $pool->getItem('report:daily');
if (!$item->isHit()) {
$report = generateDailyReport();
$item->set($report);
$item->expiresAfter(86400); // 24 小时
$pool->save($item);
}
$report = $item->get();文件结构
FileDriver 使用以下文件结构:
cache/
├── 3f8a9c2b...e1.cache # 缓存文件(文件名 = sha256(键) 的十六进制)
├── 7b41d0aa...9c.cache
└── ...每个缓存文件是 PHP serialize() 编码的数组(版本 v2):
[
'data' => ['return' => $value], // 缓存值
'expiration' => 1772529300, // 过期时间戳
'version' => 'v2', // 文件格式版本
]为什么是 serialize 而不是 JSON
早期版本用 json_encode 存 payload,代价是:对象值往返后变成数组、 非 UTF-8 二进制直接写入失败。现在的 payload 用 serialize() 编码, 对象与二进制值都能原样往返;代价是缓存文件不再是跨语言可读的 JSON。 版本号不匹配(v1 的 JSON 文件)、反序列化失败、缺字段的文件都会在读取时 被删除并按 miss 处理。
文件操作
FileDriver 使用以下策略确保文件操作的安全:
- 原子写入:先写入临时文件,再原子重命名(临时文件名带 pid + 随机串, 多线程 worker 也不会互相覆盖)
- 权限收敛:缓存目录
0700、缓存文件0600——仅本用户可读写 - 目录校验:构造时校验目录属主(他人拥有的目录拒绝使用)并拒绝软链 目录,防止共享 /tmp 上同名目录被抢先创建后的载荷注入
- 版本检查:读取时检查文件版本,版本不符即删除
- 过期清理:读取到过期条目即删除;
purge()批量清理过期文件 - 协程安全:Swoole 环境下使用协程安全操作
<?php
// 文件写入过程
$tempPath = $filePath . '.tmp.' . getmypid() . '-' . bin2hex(random_bytes(8));
file_put_contents($tempPath, $payload, LOCK_EX); // 写入临时文件
chmod($tempPath, 0600);
rename($tempPath, $filePath); // 原子性重命名性能特点
| 指标 | 值 | 说明 |
|---|---|---|
| 读取速度 | 中等 | 受磁盘 I/O 影响 |
| 写入速度 | 慢 | 受磁盘 I/O 影响 |
| 持久化 | 是 | 数据持久化到磁盘 |
| 跨进程共享 | 是 | 支持多进程共享 |
| 容量限制 | 无 | 受磁盘空间限制 |
RedisDriver
RedisDriver 使用 Redis 作为缓存存储,提供高性能的分布式缓存。
连接方式与扩展要求
kuiper/cache 的 ext-redis 已降为 suggest:RedisFactory::createConnection() 支持纯 PHP 的 predis/predis(未装扩展时可用);但容器里的 redis Bean 只支持 ext-redis。启用 Redis 缓存(L3)时按需二选一。
特性
- 存储介质:Redis
- 高性能:基于内存的高性能缓存
- 分布式支持:不支持 Redis 集群——
RedisDriver只接受单个\Redis连接, 传入RedisCluster/RedisArray/ predis 客户端会在装配期抛异常 - 键名哈希:最终 Redis 键为
prefix + md5(...),避免键名过长 - 级联失效:仅对以
group.开头的键生效(内部机制,见下文说明) - 反序列化白名单:
allowed_classes默认false(Redis 是信任边界,防止 PHP 对象注入);白名单外的对象按 miss 处理并记录 warning 日志 - 失败降级:读失败、反序列化失败、
__PHP_Incomplete_Class(含嵌套在 数组或对象属性里的实例,见统一语义)都按 miss 处理并记录 warning(需要注入 logger 才可见,框架装配时由CacheConfiguration注入);写失败返回false - 精确删除:
delete()只删当前键(键不存在视为成功),CacheItemPool::deleteItem()走该路径
配置参数
<?php
use kuiper\cache\stash\driver\RedisDriver;
use Redis;
$redis = new Redis();
$redis->connect('localhost', 6379);
$driver = new RedisDriver([
'redis' => $redis, // \Redis 实例(必填)
'prefix' => 'myapp:', // 键前缀(共享 Redis 时必配)
'allowed_classes' => false, // 反序列化白名单:false / true / 类名数组
//(元素可为精确类名或 'App\Dto\*' 通配前缀)
'index_cache_ttl' => 1, // 分组索引版本号本地缓存 TTL(秒),0 = 禁用
]);驱动选项键名统一 snake_case
RedisDriver(allowed_classes、index_cache_ttl)与 Ephemeral (max_items、max_lifetime、allowed_classes 等)的选项键名统一为 snake_case(Ephemeral 早期的 camelCase 键保留为 deprecated 别名)。 框架配置 application.cache.redis.allowed_classes 的值会原样传给 RedisDriver 的 allowed_classes 选项,所以配置文件这一层始终是 snake_case。
使用示例
<?php
declare(strict_types=1);
use kuiper\cache\stash\CacheItemPool;
use kuiper\cache\stash\driver\RedisDriver;
use Redis;
$redis = new Redis();
$redis->connect('localhost', 6379);
$driver = new RedisDriver([
'redis' => $redis,
'prefix' => 'myapp:',
]);
$pool = new CacheItemPool($driver);
// 使用缓存
$item = $pool->getItem('user:123');
if (!$item->isHit()) {
$user = fetchUserFromDatabase(123);
$item->set($user);
$item->expiresAfter(3600);
$pool->save($item);
}
$user = $item->get();Redis 键的映射规则
RedisDriver 的键映射规则以源码 RedisDriver::makeKeyString() / normalizeKeys() 为准:
- 原始键按
/分段,每段先做一次 md5(normalizeKeys()); - 不以
group.开头的普通键,返回prefix . md5(全部分段的 md5 用 '_' 拼接)并提前返回,每一段都参与键名计算; - 只有以
group.开头的键才走多级索引(:pathdb::索引键 + 递增索引),支持级联失效。
因此普通键的实际映射是:
| 原始键 | 实际 Redis 键 |
|---|---|
simple | prefix + md5(md5('simple')) |
user | prefix + md5(md5('user')) |
user/profile | prefix + md5(md5('user').'_'.md5('profile')) |
user/profile/123 | prefix + md5(md5('user').'_'.md5('profile').'_'.md5('123')) |
单段键的键名与历史版本完全一致(分段拼接对单段键就是该段本身),升级不会使已有缓存失效; 多段路径键把所有分段都算进键名,与同首段的一级键(如 user 与 user/profile)映射到不同的 Redis 键。
多段路径键不支持级联删除
普通键(含多段路径键)的 deleteItem() 只删除精确键,不会级联失效 user/ 下的子键; 需要级联失效请使用 group. 前缀键。另外分段以 / 分隔,: 不是分隔符(user:123 仍是单段键)。
批量清理时按业务约定维护键集合,或使用独立的 Redis DB / 前缀。
性能特点
| 指标 | 值 | 说明 |
|---|---|---|
| 读取速度 | 极快 | 内存访问 |
| 写入速度 | 极快 | 内存访问 |
| 持久化 | 可选 | Redis RDB/AOF |
| 分布式支持 | 否 | 不支持 Redis 集群(RedisDriver 只接受单个 \Redis 连接) |
| 容量限制 | 有 | 受 Redis 内存限制 |
clear(null) 按 SCAN 清理本驱动命名空间
RedisDriver::clear(null) 会按 prefix + 32 位 hex 的键形 SCAN 并删除本驱动的数据键与 :pathdb:: 索引键,并重置本地分组索引缓存;其它前缀或非 md5 形态的键不受影响。 共享 Redis 时请务必配置 namespace(prefix 为空时任意 32 位 hex 键都在本驱动的 清理范围内)。purge() 仍是空操作;clear($key) 对普通键只删除精确匹配的键, 对 group. 开头的分组键还会递增索引版本号,使整组子键一次性失效(级联失效)。
Composite
Composite 是复合驱动,可以组合多个缓存驱动,实现多级缓存。
特性
- 多级缓存:支持 L1、L2、L3 多级缓存
- 自动同步:读取时把命中层的条目回填到 miss 的层(含回填过期时间, 回填失败只记 warning 不中断)
- 容错机制:部分驱动故障不抛异常;写/删/清路径逐层执行并聚合结果, 任一层失败整体返回
false(失败不会静默吞掉) - 读取优化:从最快的缓存开始读取
- 精确删除:
delete()从后往前对每一层精确删除;clear($key)按 键树语义对每一层级联删除(分组键的级联失效由RedisDriver的索引 递增实现)
配置参数
<?php
use kuiper\cache\stash\driver\Composite;
$composite = new Composite([
'drivers' => [
$ephemeralDriver, // L1 缓存
$fileDriver, // L2 缓存
$redisDriver, // L3 缓存
],
]);读取策略
读取顺序:L1 → L2 → L3
1. 尝试从 L1(内存)读取
- 命中:返回数据
- 未命中:继续 L2
2. 尝试从 L2(文件)读取
- 命中:返回数据,同步到 L1
- 未命中:继续 L3
3. 尝试从 L3(Redis)读取
- 命中:返回数据,同步到 L2、L1
- 未命中:返回 null写入策略
写入顺序:L3 → L2 → L1
写入时,数据会同时写入所有驱动,
确保各级缓存数据一致。使用示例
<?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;
// 创建各级驱动
$level1 = new Ephemeral(['max_items' => 1000]);
$level2 = new FileDriver(['dir' => '/tmp/cache']);
$level3 = new RedisDriver(['redis' => $redis]);
// 组合驱动
$composite = new Composite([
'drivers' => [$level1, $level2, $level3],
]);
$pool = new CacheItemPool($composite);
// 使用多级缓存
$item = $pool->getItem('user:123');
if (!$item->isHit()) {
$user = fetchUserFromDatabase(123);
$item->set($user);
$item->expiresAfter(3600);
$pool->save($item); // 自动写入所有级别
}
$user = $item->get(); // 返回刚写入的值(条目内存值)性能特点
| 指标 | 值 | 说明 |
|---|---|---|
| L1 命中率 | 高 | 热点数据 |
| L2 命中率 | 中 | 中频数据 |
| L3 命中率 | 低 | 冷数据 |
| 总体性能 | 优秀 | 多级缓存优化 |
驱动选择建议
场景分析
| 场景 | 推荐驱动 | 原因 |
|---|---|---|
| 单进程应用 | ArrayCache | 简单高效 |
| 多进程应用 | FileDriver | 跨进程共享 |
| 高性能需求 | RedisDriver | 内存访问 |
| 分布式系统 | RedisDriver | 分布式支持 |
| 测试环境 | ArrayCache | 无外部依赖 |
| 生产环境 | Composite | 多级缓存 |
性能对比
读取速度(从快到慢):
Ephemeral > ArrayCache > RedisDriver > FileDriver
写入速度(从快到慢):
Ephemeral > ArrayCache > RedisDriver > FileDriver
容量限制(从小到大):
ArrayCache < Ephemeral < RedisDriver < FileDriver决策树
需要分布式缓存?
├─ 是 → RedisDriver
└─ 否 → 需要跨进程共享?
├─ 是 → FileDriver
└─ 否 → ArrayCache 或 Ephemeral
├─ 需要自动清理? → Ephemeral
└─ 简单场景 → ArrayCache驱动配置示例
开发环境
<?php
return [
'application' => [
'cache' => [
'memory' => [
'enabled' => true,
'max_items' => 500,
],
],
],
];测试环境
<?php
return [
'application' => [
'cache' => [
'memory' => [
'enabled' => true,
'max_items' => 1000,
],
'file' => [
'enabled' => true,
'dir' => '/tmp/test-cache',
],
],
],
];生产环境
<?php
return [
'application' => [
'cache' => [
'memory' => [
'enabled' => true,
'max_items' => 10000,
],
'file' => [
'enabled' => true,
'dir' => '/var/cache/kuiper',
],
],
'redis' => [
'host' => 'redis.internal',
'port' => 6379,
],
],
];自定义驱动
实现自定义驱动
<?php
declare(strict_types=1);
namespace App\Cache;
use kuiper\cache\stash\driver\AbstractDriver;
class MemcachedDriver extends AbstractDriver
{
private \Memcached $memcached;
protected function setOptions(array $options = []): void
{
$this->memcached = new \Memcached();
$this->memcached->addServer(
$options['host'] ?? 'localhost',
$options['port'] ?? 11211
);
}
public function getData(string $key): array
{
$data = $this->memcached->get($this->prefixKey($key));
if (false === $data) {
return [];
}
return $data;
}
public function storeData(string $key, mixed $data, int $expiration): bool
{
$cacheData = [
'data' => $data,
'expiration' => $expiration,
];
return $this->memcached->set(
$this->prefixKey($key),
$cacheData,
$expiration - time()
);
}
public function clear(?string $key = null): bool
{
if (null === $key) {
return $this->memcached->flush();
}
return $this->memcached->delete($this->prefixKey($key));
}
/**
* 精确删除单个键(可选)。
*
* 不实现也能工作:AbstractDriver 默认降级为 clear($key),
* 但那是「键树」语义(会连带删掉子键),与 deleteItem() 的
* 精确删除语义不同,Memcached 这类不支持前缀扫描的存储建议覆写。
*/
public function delete(string $key): bool
{
return $this->memcached->delete($this->prefixKey($key));
}
public function purge(): bool
{
// Memcached 自动清理过期项
return true;
}
private function prefixKey(string $key): string
{
return 'cache:'.$key;
}
}使用自定义驱动
<?php
use App\Cache\MemcachedDriver;
use kuiper\cache\stash\CacheItemPool;
use kuiper\di\attribute\Bean;
use kuiper\di\attribute\Configuration;
use Psr\Cache\CacheItemPoolInterface;
#[Configuration]
class MemcachedCacheConfiguration
{
#[Bean]
public function memcachedDriver(): MemcachedDriver
{
return new MemcachedDriver([
'host' => 'localhost',
'port' => 11211,
]);
}
#[Bean('memcachedCache')]
public function memcachedCache(MemcachedDriver $driver): CacheItemPoolInterface
{
$pool = new CacheItemPool($driver);
$pool->setDefaultTtl(3600);
return $pool;
}
}最佳实践
- 根据场景选择驱动:不同环境使用不同驱动配置
- 合理设置容量:避免内存溢出
- 使用多级缓存:提高缓存命中率
- 监控缓存性能:定期检查缓存命中率
- 定期清理缓存:避免缓存数据过多
- 设置合理的 TTL:平衡性能和数据新鲜度