🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 缓存 缓存组件通常用于缓存某些信息,避免过多的数据库查询或大量计算。 | 类 | 调用 | | --- | --- | | Mix\Cache\Cache | app()->cache | >[success] 缓存组件实现了 Psr\SimpleCache\CacheInterface ,符合 PSR 标准。 ## 依赖注入配置 [>> 到 GitHub 查看默认配置 <<](https://github.com/mix-php/mix/blob/v2/applications/http/config/main_coroutine.php#L398) >[info] 缓存组件支持 FileHandler / RedisHandler 两种处理器 ### FileHandler (默认) 依赖配置如下: ~~~ // 文件缓存 [ // 类路径 'class' => Mix\Cache\Cache::class, // 属性 'properties' => [ // 处理器 'handler' => [ 'ref' => beanname(Mix\Cache\FileHandler::class), ], ], ], // 文件缓存处理器 [ // 类路径 'class' => Mix\Cache\FileHandler::class, // 属性 'properties' => [ // 缓存目录 'dir' => 'cache', // 分区 'partitions' => 64, ], ], ~~~ ### RedisHandler 依赖配置如下: ~~~ // 文件缓存 [ // 类路径 'class' => Mix\Cache\Cache::class, // 属性 'properties' => [ // 处理器 'handler' => [ 'ref' => beanname(Mix\Cache\RedisHandler::class), ], ], ], // redis缓存处理器 [ // 类路径 'class' => Mix\Cache\RedisHandler::class, // 属性 'properties' => [ // 连接 'connection' => [ // 引用组件 'component' => 'redis', ], // Key前缀 'keyPrefix' => 'CACHE:', ], ], ~~~ 在协程模式下还支持连接池配置,修改 RedisHandler 如下: ~~~ // redis缓存处理器 [ // 类路径 'class' => Mix\Cache\RedisHandler::class, // 属性 'properties' => [ // 连接池 'pool' => [ // 引用组件 'component' => 'redisPool', ], // Key前缀 'keyPrefix' => 'CACHE:', ], ], ~~~ ## 方法 ``` // 获取缓存 app()->cache->get($key, $default); // 设置缓存 app()->cache->set($key, $value, $ttl); // 删除缓存 app()->cache->delete($key); // 清除缓存 app()->cache->clear(); // 批量获取 app()->cache->getMultiple($keys, $default); // 批量设置 app()->cache->setMultiple($values, $ttl); // 批量删除 app()->cache->deleteMultiple($keys); // 判断缓存是否存在 app()->cache->has($key); ```