缓存驱动

Viswoole 缓存系统采用驱动架构,支持多种存储后端。每个驱动实现统一的 CacheDriverInterface 接口,确保 API 一致性。

内置驱动

File 文件驱动

将缓存数据以序列化形式存储在本地文件系统中。

特性

  • 无需外部依赖,开箱即用
  • 通过文件头部嵌入过期时间戳实现 TTL 管理
  • 支持文件锁实现的竞争锁机制
  • 自动清理过期文件和空目录

配置示例

php
// config/cache.php
return [
    'default' => 'file',
    'stores' => [
        'file' => \Viswoole\Cache\Facade\Cache::FILE_DRIVER,
    ]
];

构造参数

php
new \Viswoole\Cache\Driver\File(
    storage: BASE_PATH . '/runtime/cache',  // 存储根目录
    prefix: '',                              // 键前缀
    tag_prefix: 'tag:',                      // 标签前缀
    tag_store: 'TAG_STORE',                  // 标签仓库名称
    expire: 0                                // 默认过期时间(0=永不过期)
);

存储结构

text
runtime/cache/
├── key1                          # 缓存文件
├── key2
├── lock/                         # 锁文件目录
│   └── order:create              # 锁文件
└── sub/
    └── namespace:key             # 支持子目录命名空间

适用场景

  • 开发环境快速验证
  • 小型应用或单机部署
  • 无 Redis 环境的轻量场景

Redis 驱动

基于 Redis 的高性能缓存驱动,支持连接池管理和原子操作。

特性

  • 原生支持 TTL、原子自增/自减
  • 基于 Redis SET NX EX 的分布式锁
  • 协程安全的连接池复用
  • 整数类型优化存储(跳过序列化)

配置示例

php
// config/cache.php
use Viswoole\Cache\Facade\Cache;

return [
    'default' => 'redis',
    'stores' => [
        'redis' => [
            'driver' => Cache::REDIS_DRIVER,
            'options' => [
                'host' => env('REDIS_HOST', '127.0.0.1'),
                'port' => env('REDIS_PORT', 6379),
                'password' => env('REDIS_PASSWORD', ''),
                'db_index' => env('REDIS_DB', 0),
                'prefix' => 'app:',
                'expire' => 3600,
                'pool_max_size' => 64,
                'pool_fill_size' => 10,
            ]
        ]
    ]
];

构造参数

参数类型默认值说明
hoststring127.0.0.1Redis 服务器地址
portint6379Redis 服务器端口
passwordstring''认证密码
db_indexint0数据库索引(0-15)
timeoutfloat0连接超时时间(秒)
retry_intervalint1000重连间隔(毫秒)
read_timeoutfloat0读取超时时间(秒)
prefixstring''键名前缀
tag_prefixstring'tag:'标签键前缀
expireint0默认过期时间(秒)
tag_storestring'TAG_STORE'标签仓库名称
pool_max_sizeint64连接池最大连接数
pool_fill_sizeint0预填充连接数

RedisConfig 与 RedisPool

框架提供独立的配置类和连接池管理:

php
use Viswoole\Cache\RedisConfig;
use Viswoole\Cache\RedisPool;

// 创建配置
$config = new RedisConfig(
    host: '127.0.0.1',
    port: 6379,
    password: '',
    pool_max_size: 64
);

// 创建连接池
$pool = new RedisPool($config);

// 借出/归还连接
$redis = $pool->pop();   // 借出连接
$pool->put($redis);      // 归还连接

数据类型处理

Redis 驱动对数据类型做了特殊优化:

php
// 整数直接存储,不走序列化
Cache::set('counter', 42);
Cache::get('counter');   // 返回 int(42),非字符串

// 浮点数同样优化
Cache::set('price', 99.99);
Cache::get('price');     // 返回 float(99.99)

// 复杂对象走标准序列化
Cache::set('user', ['name' => '张三']);
Cache::get('user');      // 返回数组

数组集合(Set 操作)

php
// 使用 Redis Set 实现数组集合
Cache::sAddArray('permissions', ['read', 'write', 'delete']);
Cache::sAddArray('permissions', 'execute');

$perms = Cache::getArray('permissions');
// 返回: ['read', 'write', 'delete', 'execute']

Cache::sRemoveArray('permissions', ['delete']);

适用场景

  • 生产环境高性能缓存
  • 分布式部署多实例共享
  • 需要原子操作的计数器场景
  • 高并发分布式锁需求

驱动对比

特性FileRedis
性能低(磁盘 I/O)高(内存操作)
部署依赖需要 Redis 服务
分布式支持不支持原生支持
数据持久化文件系统可配置(RDB/AOF)
连接管理连接池
推荐环境开发/测试生产环境

自定义驱动

实现 CacheDriverInterface 接口即可创建自定义缓存驱动:

php
use Viswoole\Cache\Contract\CacheDriverInterface;

class MemcachedDriver implements CacheDriverInterface
{
    public function get(string $key, mixed $default = null): mixed
    {
        // 实现获取逻辑
    }

    public function set(string $key, mixed $value, DateTime|int|null $expire = null, bool $NX = false): bool
    {
        // 实现设置逻辑
    }

    public function delete(array|string $keys): false|int
    {
        // 实现删除逻辑
    }

    public function has(string $key): bool
    {
        // 实现判断逻辑
    }

    public function clear(): bool
    {
        // 实现清除逻辑
    }

    // ... 其他接口方法
}

// 注册自定义驱动
Cache::addStore('memcached', new MemcachedDriver());
Cache::store('memcached')->set('key', 'value');