StartMVC开发手册

可以快速上手的开发文档

手册目录

缓存基本用法

基本介绍

StartMVC框架提供了轻量级的缓存系统,支持文件(File)、Redis、Memcached三种缓存驱动,满足不同场景的缓存需求。缓存系统可以有效提升应用性能,减轻数据库负载。三种驱动的方法完全一致,切换驱动只需修改一行配置。

配置说明

缓存配置位于config/cache.php文件中:

return [
 'drive' => 'file', // 默认缓存驱动,支持file、redis、memcached
 'file'=> [ // 文件缓存配置
 'cacheDir'=>'cache/', // 缓存目录(runtime/下,带不带尾斜杠均可)
 'cacheTime'=>3600 // 默认缓存时间(秒)
 ],
 'redis' => [ // Redis缓存配置
 'host' => '127.0.0.1', // Redis服务器地址
 'port' => 6379, // Redis端口
 'password' => '', // Redis密码
 'database' => 0, // Redis数据库索引
 'cacheTime'=>3600 // 默认缓存时间(秒)
 ],
 'memcached' => [ // Memcached缓存配置
 'host' => '127.0.0.1', // Memcached服务器地址
 'port' => 11211, // Memcached端口
 'cacheTime'=>3600 // 默认缓存时间(秒)
 ],
];

cacheTime为该驱动的默认缓存时间,调用时不传入有效期参数时使用该值。

基本用法

创建缓存实例
use startmvc\core\Cache;

// 使用默认驱动
$cache = Cache::store();

// 指定驱动
$redis = Cache::store('redis');

// 也可以直接实例化
$cache = new Cache();
$redis = new Cache('redis');

自v2.9.4起,Cache::store()内置实例池:同一驱动只创建一次连接,重复调用返回同一实例,避免重复连接Redis/Memcached。

设置缓存
// 第三个参数为有效期(秒),不传则使用驱动配置的cacheTime
$cache->set('key', 'value');
$cache->set('key', 'value', 300); // 缓存300秒

// 返回bool,表示是否写入成功
$ok = $cache->set('key', 'value', 300);

注意:v2.9.4起set()返回bool(是否写入成功),不再返回$this,不再支持链式调用

获取缓存
// 获取缓存,未命中或已过期返回null
$value = $cache->get('key');

// 判断缓存是否存在且有效
if ($cache->has('key')) {
 // 缓存存在
}
删除缓存
// 删除单个缓存,返回bool(键不存在时为false)
$cache->delete('key');

// 清空该驱动下所有缓存
$cache->clear();

remember()读取或写入(v2.9.4新增)

最常用的缓存模式:命中直接返回,未命中时执行回调取值并写入缓存,一行代码完成"读缓存→取数据→写缓存":

$users = $cache->remember('user:all', function () {
 return db('user')->select(); // 仅在缓存未命中时执行
}, 600); // 缓存600秒
  • 回调返回null视为不可缓存,不会写入,下次仍会执行回调(因此不要缓存null值)。
  • 高并发下同一key的回调可能同时执行(无锁),对必须单次执行的场景请自行加锁,详见缓存高级用法

助手函数cache()使用方法

cache($name, $value = null, $ttl = null, $driver = null)

//$name 缓存名称(注意命名唯一性,防止重复)
//$value 缓存值:null表示获取,false表示删除,其他值表示设置
//$ttl 缓存时间(秒),null时使用驱动配置的默认cacheTime
//$driver 缓存驱动,默认使用配置中的驱动

// 设置缓存:7200秒
cache('user_profile_1001', $userData, 7200);

// 设置缓存:不传ttl,使用驱动配置的默认cacheTime
cache('site_config', $config);

// 获取缓存(未命中返回null)
$userData = cache('user_profile_1001');

// 删除缓存
cache('user_profile_1001', false);

// 使用Redis驱动
cache('hot_products', $products, 1800, 'redis');

注意(v2.9.4变更):第三个参数默认值由固定的3600改为null:不传TTL时使用驱动配置的cacheTime而非写死3600;显式传入3600也会正常生效(旧版会被误判为未传参而改用默认值)。

方法速查表

方法说明返回值
Cache::store($driver, $params)获取缓存实例,同驱动复用连接Cache
set($key, $val, $ttl = null)写入缓存,$ttl为秒数,null用驱动默认bool
get($key)读取缓存mixed,未命中为null
has($key)缓存是否存在且未过期bool
remember($key, $callback, $ttl = null)未命中时执行回调并写入(v2.9.4新增)mixed
delete($key)删除单个缓存bool
clear()清空当前驱动所有缓存$this