Houze 文档 / 缓存 / Cache

缓存

Cache

缓存层统一入口是 houze\Cache,驱动可切换 file / memory / redis,接口一致。

用法

$cache = new \houze\Cache();

$cache->set('key', $value, 60);   // 值 / 有效期(秒,0 永久)
$cache->get('key');
$cache->has('key');
$cache->rm('key');                // 删除
$cache->pull('key');              // 取出并删除
$cache->inc('pv');                // 自增
$cache->dec('pv');

需要换驱动时:(new \houze\Cache('redis'))->set(...),参数是 config/cache.php 里的配置键名。

三种驱动

驱动存储适用
fileruntime/ 下的文件单机、量小、允许稍慢
memory进程内存只在当前进程有效,重启即失
redisRedis多实例共享,生产推荐

配置

// config/cache.php
'default' => [
    'type'   => 'redis',
    'expire' => 0,
    'prefix' => 'hz_',
],

缓存三件套写法

$cache = new \houze\Cache();
$key = 'article_' . $id;

$row = $cache->get($key);
if ($row === null) {
    $row = db()->table('article_data')->where('id', $id)->find();
    $cache->set($key, $row, 300);
}
return $this->api(0, 'ok', $row);

坑

  • memory 驱动在单进程里没问题,但多实例之间不共享,别拿它做分布式锁;
  • 内容更新后要主动 rm(),否则用户看到的是旧数据;
  • 键名带前缀 hz_,与别的系统共用 Redis 时不会打架。

最后更新:2026-12-02 · 本文档对应 Houze v2.5.9,如有出入以框架源码为准。