缓存配置
概述
Kuiper 框架的缓存配置通过 CacheConfiguration 类实现,它负责配置和构建缓存实例。通过灵活的配置选项,可以轻松切换不同的缓存驱动和缓存策略。
配置文件结构
缓存配置位于 src/config.php 文件中:
<?php
declare(strict_types=1);
return [
'application' => [
'cache' => [
// 缓存实现类型(可选)
'implementation' => null,
// 缓存命名空间,用于隔离不同应用的缓存
'namespace' => 'myapp',
// 默认缓存生命周期(秒),0 表示使用内置默认的 300 秒(不是永久缓存)
'lifetime' => 3600,
// 内存缓存配置
'memory' => [
'enabled' => true, // 是否启用内存缓存
'lifetime' => 60, // L1 条目最大存活时间(秒),原样作为 Ephemeral 的 max_lifetime,无倍数换算
'max_items' => 1000, // 最大缓存项数
'serialize' => false, // 是否序列化存储
// 'allowed_classes' => true, // L1 反序列化白名单(默认 true;见缓存驱动文档)
],
// 文件缓存配置
'file' => [
'enabled' => false, // 是否启用文件缓存
'dir' => '/tmp/kuiper-cache', // 缓存目录
// 注意:ttl 选项当前不会被 FileDriver 消费,条目 TTL 由上面的 lifetime / expiresAfter() 决定
],
// 元数据缓存配置
'metadata' => [
'enabled' => true, // 是否启用元数据缓存
'dir' => '/tmp/kuiper-metadata-cache', // 缓存目录
// 注意:ttl 选项当前不会被 FileDriver 消费
],
// Redis 缓存(L3):enabled 子键控制是否挂载 Redis 驱动;
// null 或不配置表示不启用;连接信息见下方 application.redis
// 'redis' => ['enabled' => true],
],
// Redis 配置(用于 Redis 缓存驱动)
'redis' => [
'host' => 'localhost',
'port' => 6379,
'password' => null,
'database' => 0,
],
],
];显式配置 application.cache.redis 节点:0.9.4-RC3 及之前等价于「启用」,CACHE_REDIS_ENABLED=false 不再生效
CacheConfiguration 用 mergeWhenAbsent() 装配缓存默认值:只有 application.cache.redis 键不存在时才写入缺省值 (由 CACHE_REDIS_ENABLED 决定,默认不挂载)。应用配置里一旦显式写了该节点 (典型是给 Redis 缓存配 allowed_classes 白名单),mergeWhenAbsent 不再覆盖它, 0.9.4-RC3 的装配层按「节点存在 = 挂载 Redis 驱动」处理(isset($options['redis']))—— 环境变量里的 CACHE_REDIS_ENABLED=false 被无声跳过,Redis 层照常挂载。
下游实测(ip-server):为对象缓存白名单显式配置了 application.cache.redis.allowed_classes 后,测试环境依赖 CACHE_REDIS_ENABLED=false 关闭 Redis 层失效,查询命中了本地 Redis 里 早前写入的缓存。
- 修复:v0.9.4 正式版归一化挂载语义(提交
f35309a1)——挂载改由application.cache.redis的enabled子键显式控制:显式节点 +'enabled' => false可以关闭;显式节点未写enabled仍默认启用; - RC3 及更早版本的规避:想禁用 Redis 层就不要配置该节点(连空数组也不要); 显式配置节点即视为启用,此时开关只有配置本身;
- 自查(RC3):
var_dump($container->get('application.cache')['redis'])—— 显式配置场景下它是数组而非null。
Metadata Cache 配置
Metadata Cache 是专门为框架内部元数据(如反射信息、Use 语句解析结果等)设计的缓存池。它可以显著提高框架处理反射和元数据相关操作的性能。
设计理念
Metadata Cache 采用仅文件缓存的设计策略。这是因为:
- 应用层内存缓存: 使用 metadataCache 的应用(如
UseStatementCache)已经实现了自己的进程内内存缓存机制 - 避免重复缓存: 不在 metadataCache 中添加额外的内存缓存层,避免资源浪费
- 持久化优先: metadataCache 主要提供跨请求的持久化存储,文件缓存是最佳选择
启用/禁用元数据缓存
可以通过配置文件或环境变量控制元数据缓存的启用状态:
// 通过配置文件
return [
'application' => [
'cache' => [
'metadata' => [
'enabled' => true, // 启用元数据缓存
'dir' => '/var/cache/kuiper/metadata', // 缓存目录
// 'ttl' => 3600, // 注意:该选项当前不会被 FileDriver 消费
],
],
],
];或者通过环境变量:
export CACHE_METADATA_ENABLED=true
export CACHE_METADATA_FILE_DIR=/var/cache/kuiper/metadata
# 注意:CACHE_METADATA_FILE_TTL 不被任何代码读取(配置项与该环境变量均无效)配置示例
// 生产环境配置
return [
'application' => [
'cache' => [
'metadata' => [
'enabled' => true,
'dir' => '/var/cache/kuiper/metadata',
],
],
],
];
// 开发环境配置
return [
'application' => [
'cache' => [
'metadata' => [
'enabled' => false, // 开发环境可以禁用以立即看到变更
],
],
],
];metadata.ttl 当前不生效
元数据缓存由 FileDriver 支撑,而 FileDriver 并不消费 ttl 选项。若需要更长的元数据缓存时间,请在创建 metadataCache 后调用 setDefaultTtl(),或调整全局 application.cache.lifetime。
环境变量配置
# 启用元数据缓存
export CACHE_METADATA_ENABLED=true
# 文件缓存配置
export CACHE_METADATA_FILE_DIR=/tmp/kuiper-metadata-cache
# 注意:CACHE_METADATA_FILE_TTL 不被任何代码读取(配置项与该环境变量均无效)内部实现
Metadata Cache 在启用时直接返回基于 FileDriver 的缓存池:
#[Bean('metadataCache')]
public function metadataCache(ContainerInterface $container): CacheItemPoolInterface
{
$options = $container->get('application.cache.metadata');
// 如果元数据缓存未启用,则返回内存缓存
if (!isset($options['enabled']) || !$options['enabled']) {
return $container->get('memoryCache');
}
return new CacheItemPool(new FileDriver($options));
}使用场景
Metadata Cache 主要用于以下场景:
- Use Statement 缓存:
UseStatementCache使用 metadataCache 缓存 PHP 文件的 use 语句解析结果 - 反射信息缓存: 缓存反射操作的中间结果
- 元数据持久化: 任何需要跨请求持久化的元数据
性能优化建议
- 生产环境: 启用 metadataCache 并使用高速存储(如 SSD)
- 开发环境: 可以禁用 metadataCache 以便立即看到代码变更效果
- 缓存目录: 使用专用目录,定期清理过期缓存文件
CacheConfiguration 类
CacheConfiguration 是缓存配置的核心类,负责:
- 加载和合并缓存配置
- 创建 Redis 连接
- 配置各种缓存驱动
- 构建 PSR-6 和 PSR-16 缓存实例
类定义
<?php
declare(strict_types=1);
namespace kuiper\cache;
use kuiper\di\DefinitionConfiguration;
use kuiper\helper\ConfigAwareInterface;
use kuiper\helper\ConfigAwareTrait;
// 注意:该类没有 #[Configuration] 属性,不会被组件扫描发现
class CacheConfiguration implements DefinitionConfiguration, ConfigAwareInterface
{
use ConfigAwareTrait;
// Bean 定义方法...
}CacheConfiguration 虽然没有 #[Configuration] 属性(组件扫描发现不了它),但它已在 cache/composer.json 与根 composer.json 的 extra.kuiper.configuration 中登记, 标准 Runtime 会通过 AutoConfigurationLoader 聚合这些声明并自动注册该配置类 (见运行时配置文档), 业务应用无需在 container.php 手工列出。
手工构建容器时才需要显式注册
只有在绕过 Runtime 手工构建 ContainerBuilder(例如单元测试里直接 new ContainerBuilder(...))时,extra.kuiper.configuration 的自动装配清单不会生效, 此时必须显式注册,否则缓存相关 Bean 不会存在,运行时抛 InvalidDefinition:
<?php
declare(strict_types=1);
use kuiper\cache\CacheConfiguration;
use kuiper\di\ContainerBuilder;
use kuiper\helper\Config;
$builder = new ContainerBuilder(
require __DIR__.'/vendor/autoload.php',
Config::create([])
);
// addConfiguration(object $configuration): self
$builder->addConfiguration(new CacheConfiguration());
$container = $builder->build();核心 Bean 方法
1. Redis 连接 Bean
#[Bean]
public function redis(
ContainerInterface $container,
#[Inject('application.redis')] ?array $redisConfig
): \Redis {
if (!isset($redisConfig)) {
$redisConfig = [];
}
$connect = static function () use ($redisConfig) {
return RedisFactory::createConnection(
RedisFactory::buildDsn($redisConfig),
$redisConfig
);
};
// Swoole 环境下使用连接池
if (Coroutine::isEnabled()) {
return ConnectionProxyGenerator::create(
$container->get(PoolFactoryInterface::class),
\Redis::class,
$connect
);
}
return $connect();
}2. 内存缓存 Bean
#[Bean('memoryCache')]
public function memoryCache(Ephemeral $driver): CacheItemPoolInterface
{
return new CacheItemPool($driver);
}3. Ephemeral 驱动 Bean
#[Bean]
public function stashEphemeralDriver(
#[Inject('application.cache.memory')] ?array $config
): Ephemeral {
$config = $config ?? [];
// 'enabled' 是装配开关、'lifetime' 是配置面键名,都不是驱动选项
// (Ephemeral 对未知选项显式抛 InvalidArgumentException)
unset($config['enabled']);
$lifetime = $config['lifetime'] ?? 0;
unset($config['lifetime']);
// memory.lifetime > 0 时原样换算为 max_lifetime(无倍数);
// lifetime = 0(默认)表示不截断;显式配置过 max_lifetime 时以显式配置为准
if (is_numeric($lifetime) && (int) $lifetime > 0 && !isset($config['max_lifetime'])) {
$config['max_lifetime'] = (int) $lifetime;
}
return new Ephemeral($config);
}4. 文件缓存驱动 Bean
#[Bean]
public function stashFileDriver(
#[Inject('application.cache.file')] ?array $config
): FileDriver {
$config = $config ?? [];
// 兜底目录必须按 uid 隔离:共享 /tmp 上的 kuiper-cache 目录其他本地
// 用户可读缓存内容(与 FileDriver::defaultDir() 一致)
$config['dir'] = $config['dir'] ?? FileDriver::defaultDir();
// 注意:条目的过期时间由 CacheItem 的 expiration 决定(池的默认 TTL 在
// getItem() 时注入),FileDriver 不消费 'ttl' 选项——该选项此前从未生效;
// FileDriver 在构造时校验缓存目录属主并拒绝软链目录(见缓存驱动文档),
// 并支持 'allowed_classes' 反序列化白名单(默认 true)
return new FileDriver($config);
}5. 主缓存池 Bean
#[Bean]
public function cacheItemPool(ContainerInterface $container): CacheItemPoolInterface
{
$options = $container->get('application.cache');
$drivers = [];
// 1. 进程内内存缓存 (L1)
if (($options['memory']['enabled'] ?? false)) {
$drivers[] = $container->get(Ephemeral::class);
}
// 2. 文件缓存 (L2)
if (($options['file']['enabled'] ?? false)) {
$drivers[] = $container->get(FileDriver::class);
}
// 3. Redis 缓存 (L3):Redis 是信任边界,默认禁止反序列化出任意类
// (allowed_classes 白名单 ∪ 扫描到的 #[Cacheable] 类名)
if (($options['redis']['enabled'] ?? true)) {
$redisDriver = new RedisDriver([
'redis' => $container->get(\Redis::class),
'prefix' => $options['namespace'] ?? '',
'allowed_classes' => /* resolveAllowedClasses(...),见 best-practices */,
]);
$drivers[] = $redisDriver;
}
// 如果没有启用任何缓存,使用默认的 Ephemeral
if (empty($drivers)) {
$drivers[] = $container->get(Ephemeral::class);
}
$cacheItemPool = new CacheItemPool(new Composite(['drivers' => $drivers]));
// 只有 lifetime > 0 才会覆盖默认 TTL;0 保持内置默认 300 秒
$lifetime = (int) ($options['lifetime'] ?? 0);
if ($lifetime > 0) {
$cacheItemPool->setDefaultTtl($lifetime);
}
return $cacheItemPool;
}6. 简单缓存 Bean
#[Bean]
public function simpleCache(CacheItemPoolInterface $cacheItemPool): CacheInterface
{
return new SimpleCache($cacheItemPool);
}环境变量配置
缓存模块支持通过环境变量进行配置:
缓存通用配置
# 启用的缓存驱动(逗号分隔:memory,file,redis),等价于开启对应的 CACHE_*_ENABLED。
# 简写里的 redis 只负责「确保挂载」:已显式配置过 application.cache.redis
# (allowed_classes 白名单等)时原样保留;用户显式写了 enabled=false 时简写不推翻
export CACHE_IMPLEMENTATION="redis"
# 缓存命名空间
export CACHE_NAMESPACE="myapp"
# 默认缓存生命周期(秒);0 表示使用内置默认 300 秒,不是永久缓存
export CACHE_LIFETIME="3600"内存缓存配置
# 是否启用内存缓存
export CACHE_MEMORY_ENABLED="true"
# L1 条目最大存活时间上限(秒);原样作为 Ephemeral 的 max_lifetime,无倍数换算
export CACHE_MEMORY_LIFETIME="60"
# 内存缓存最大项数
export CACHE_MEMORY_MAX_ITEMS="1000"
# 是否序列化内存缓存
export CACHE_MEMORY_SERIALIZE="false"文件缓存配置
# 是否启用文件缓存
export CACHE_FILE_ENABLED="true"
# 文件缓存目录(默认按 uid 隔离;构造时会校验目录属主并拒绝软链,见缓存驱动文档)
export CACHE_FILE_DIR="/var/cache/kuiper"
# 注意:CACHE_FILE_TTL 不被任何代码读取(配置项与该环境变量均无效);
# 条目 TTL 由 CACHE_LIFETIME / expiresAfter() 决定Redis 配置
# 是否启用 Redis 缓存(L3)
# 显式设置时优先于 application.cache.redis 节点的显式配置:
# CACHE_REDIS_ENABLED=false 能关掉已显式配置的节点;
# 未设置时保持旧语义——显式配置了节点即挂载(可再用 enabled=false 显式关闭)
export CACHE_REDIS_ENABLED="true"
# Redis 主机
export REDIS_HOST="localhost"
# Redis 端口
export REDIS_PORT="6379"
# Redis 密码
export REDIS_PASSWORD="your_password"
# Redis 数据库编号
export REDIS_DATABASE="0"缓存命名空间
缓存命名空间用于隔离不同应用或模块的缓存,避免键冲突。
设置命名空间
<?php
return [
'application' => [
'cache' => [
'namespace' => 'myapp:v1',
],
],
];命名空间的作用
- 键隔离:不同命名空间的缓存键互不影响
- 版本管理:通过命名空间管理缓存版本
- 多应用支持:同一 Redis 实例支持多个应用
Redis 键命名规则
application.cache.namespace 会作为 RedisDriver 的 prefix;普通键(不以 group. 开头)的最终 Redis 键为:
{prefix}{md5(md5('段1')_md5('段2')_...)}例如(prefix = 'myapp:'):
user:123→myapp:+md5(md5('user:123'))config:db→myapp:+md5(md5('config:db'))
单段键的键名与历史版本一致,升级不会使已有缓存失效;多段路径键(以 / 分段)会把所有分段都算进键名,user、user/profile、user/profile/123 映射到不同的 Redis 键,互不覆盖。但普通键的删除仍是精确删除,不会级联删除子键,需要级联失效请使用 group. 前缀键。详细规则见缓存驱动。
与“前缀”的关系
namespace 和前缀不是两个独立的隔离层:namespace 就是传入 RedisDriver 的 prefix。需要物理隔离时,直接设置更具体的 namespace(例如 myapp:dev:)即可。
TTL 配置
TTL(Time To Live)定义了缓存项的有效期。
全局默认 TTL
<?php
return [
'application' => [
'cache' => [
'lifetime' => 3600, // 全局默认 1 小时
],
],
];lifetime 只在大于 0 时覆盖 CacheItemPool 的默认值;设置为 0(或未配置)时使用内置默认的 300 秒,并不是永久缓存。确实需要“永不过期”的条目时,可在自定义缓存池上设置一个足够大的有限值:
<?php
use kuiper\cache\stash\CacheItemPool;
$pool = new CacheItemPool($driver);
// 约 100 年。不要传 PHP_INT_MAX:
// CacheItem::expiresAfter() 会用 new DateInterval("PT{$ttl}S") 解析,过大的值会抛
// Exception: Unknown or bad format
$pool->setDefaultTtl(3153600000);驱动级 TTL
<?php
return [
'application' => [
'cache' => [
'memory' => [
// 原样作为 Ephemeral 的 max_lifetime(无倍数换算),仅限制 L1 条目最长存活时间
'lifetime' => 60,
],
'file' => [
// FileDriver 没有可用的 ttl 选项;L2 条目 TTL 由全局 lifetime / expiresAfter() 决定
],
],
],
];驱动级 TTL 的限制
memory.lifetime会原样换算成Ephemeral的max_lifetime(无倍数换算),它是上限而不是逐条 TTL;file.ttl(以及metadata.ttl)当前不会被FileDriver消费;Composite写入时会把同一个过期时间写给所有驱动,因此 L2/L3 没有独立的 TTL 配置。
单个缓存项 TTL
<?php
use Psr\Cache\CacheItemPoolInterface;
class UserService
{
public function __construct(
private readonly CacheItemPoolInterface $cache
) {
}
public function getUser(int $id): array
{
$item = $this->cache->getItem("user:{$id}");
if (!$item->isHit()) {
$user = $this->fetchFromDatabase($id);
$item->set($user);
$item->expiresAfter(300); // 该缓存项 5 分钟后过期
$this->cache->save($item);
}
return $item->get();
}
}缓存前缀
缓存前缀用于进一步隔离缓存键,通常在 Redis 驱动中使用。
配置缓存前缀
<?php
$redisDriver = new RedisDriver([
'redis' => $redis,
'prefix' => 'myapp:', // 所有键都会添加此前缀
]);前缀与命名空间的区别
| 特性 | 命名空间 | 前缀 |
|---|---|---|
| 作用范围 | Redis 驱动 | Redis 驱动 |
| 格式 | 通过 application.cache.namespace 配置 | 直接传给 RedisDriver 的 prefix |
| 用途 | 应用级隔离 | 缓存池级隔离 |
在框架默认装配中,application.cache.namespace 就是作为 RedisDriver 的 prefix 使用的,两者最终效果相同。
完整配置示例
开发环境配置
<?php
// src/config.php
return [
'application' => [
'cache' => [
'namespace' => 'myapp:dev',
'lifetime' => 300, // 开发环境短缓存时间
'memory' => [
'enabled' => true,
'lifetime' => 60,
'max_items' => 500,
'serialize' => false,
],
],
],
];生产环境配置
<?php
// src/config.php
return [
'application' => [
'cache' => [
'namespace' => 'myapp:prod',
'lifetime' => 3600,
'memory' => [
'enabled' => true,
'lifetime' => 60,
'max_items' => 10000,
'serialize' => true,
],
'file' => [
'enabled' => true,
'dir' => '/var/cache/kuiper',
],
],
'redis' => [
'host' => 'redis.internal',
'port' => 6379,
'password' => getenv('REDIS_PASSWORD'),
'database' => 0,
],
],
];使用 .env 文件配置
# .env
CACHE_NAMESPACE=myapp
CACHE_LIFETIME=3600
CACHE_MEMORY_ENABLED=true
CACHE_MEMORY_LIFETIME=60
CACHE_MEMORY_MAX_ITEMS=1000
CACHE_FILE_ENABLED=true
CACHE_FILE_DIR=/var/cache/kuiper
REDIS_HOST=redis.internal
REDIS_PORT=6379
REDIS_PASSWORD=secret
REDIS_DATABASE=0自定义缓存配置
创建自定义缓存池
<?php
use kuiper\cache\stash\CacheItemPool;
use kuiper\cache\stash\driver\RedisDriver;
use kuiper\di\attribute\Bean;
use kuiper\di\attribute\Configuration;
use Psr\Cache\CacheItemPoolInterface;
#[Configuration]
class CustomCacheConfiguration
{
#[Bean('userCache')]
public function userCache(\Redis $redis): CacheItemPoolInterface
{
$driver = new RedisDriver([
'redis' => $redis,
'prefix' => 'users:',
]);
$pool = new CacheItemPool($driver);
$pool->setDefaultTtl(600); // 用户缓存 10 分钟
return $pool;
}
#[Bean('configCache')]
public function configCache(\Redis $redis): CacheItemPoolInterface
{
$driver = new RedisDriver([
'redis' => $redis,
'prefix' => 'config:',
]);
$pool = new CacheItemPool($driver);
$pool->setDefaultTtl(86400); // 配置缓存 24 小时
return $pool;
}
}使用自定义缓存池
<?php
use DI\Attribute\Inject;
use kuiper\di\attribute\Service;
use Psr\Cache\CacheItemPoolInterface;
#[Service]
class UserRepository
{
public function __construct(
#[Inject('userCache')]
private readonly CacheItemPoolInterface $cache
) {
}
public function find(int $id): ?User
{
$item = $this->cache->getItem("user:{$id}");
if (!$item->isHit()) {
$user = $this->fetchFromDatabase($id);
$item->set($user);
$this->cache->save($item);
}
return $item->get();
}
}配置验证
验证缓存配置
<?php
use kuiper\cache\CacheConfiguration;
use kuiper\di\ContainerBuilder;
use kuiper\helper\Config;
$builder = new ContainerBuilder(
require __DIR__.'/vendor/autoload.php',
Config::create([])
);
// 手工构建容器(绕过 Runtime)时需显式注册缓存配置;
// 标准 Runtime 下由 extra.kuiper.configuration 自动装配,无需此行
$builder->addConfiguration(new CacheConfiguration());
$container = $builder->build();
// 验证 PSR-6 缓存池
$cachePool = $container->get(\Psr\Cache\CacheItemPoolInterface::class);
var_dump($cachePool instanceof \kuiper\cache\stash\CacheItemPool); // true
// 验证 PSR-16 简单缓存
$cache = $container->get(\Psr\SimpleCache\CacheInterface::class);
var_dump($cache instanceof \kuiper\cache\SimpleCache); // true
// 测试缓存操作
$cache->set('test', 'value', 60);
var_dump($cache->get('test')); // 'value'
$cache->delete('test');最佳实践
1. 根据环境选择缓存策略
<?php
$cacheConfig = [
'application' => [
'cache' => [
'namespace' => 'myapp',
'lifetime' => $isProduction ? 3600 : 300,
'memory' => [
'enabled' => true,
'max_items' => $isProduction ? 10000 : 500,
],
],
],
];2. 合理设置缓存层级
- L1(内存):热点数据,短 TTL
- L2(文件):中等频率数据,中等 TTL
- L3(Redis):冷数据,长 TTL
3. 使用命名空间隔离
<?php
$cacheConfig = [
'application' => [
'cache' => [
'namespace' => sprintf('myapp:%s:%s', $env, $version),
],
],
];4. 监控缓存命中率
<?php
class CacheMonitor
{
private int $hits = 0;
private int $misses = 0;
public function recordHit(): void
{
++$this->hits;
}
public function recordMiss(): void
{
++$this->misses;
}
public function getHitRate(): float
{
$total = $this->hits + $this->misses;
return $total > 0 ? $this->hits / $total : 0;
}
}故障排查
配置未生效
- 确认
CacheConfiguration是否已注册:标准 Runtime 会按extra.kuiper.configuration自动注册;手工构建ContainerBuilder(绕过 Runtime)时需显式$builder->addConfiguration(new CacheConfiguration()),未注册时获取缓存 Bean 会抛InvalidDefinition - 检查配置文件是否正确加载
- 验证环境变量是否设置
- 清除应用缓存
Redis 连接失败
- 验证 Redis 服务状态
- 检查连接配置
- 测试网络连通性
内存缓存溢出
- 增加
max_items配置 - 减少缓存项大小
- 启用序列化