基本介绍
StartMVC框架提供了轻量级的缓存系统,支持文件(File)和Redis两种缓存驱动,满足不同场景的缓存需求。缓存系统可以有效提升应用性能,减轻数据库负载。
配置说明
缓存配置位于config/cache.php
文件中:
return [
'drive' => 'file', // 默认缓存驱动,支持file和redis
'file'=> [ // 文件缓存配置
'cacheDir'=>'cache/', // 缓存目录
'cacheTime'=>3600 // 默认缓存时间(秒)
],
'redis' => [ // Redis缓存配置
'host' => '127.0.0.1', // Redis服务器地址
'port' => 6379, // Redis端口
'password' => '', // Redis密码
'database' => 0, // Redis数据库索引
'cacheTime'=>3600 // 默认缓存时间(秒)
],
];
基本用法
创建缓存实例
use startmvc\core\Cache;
// 使用默认驱动
$cache = new Cache();
// 指定驱动
$cache = new Cache('redis');
// 使用静态工厂方法
$cache = Cache::store('redis');
设置缓存
// 设置缓存
$cache->set('key', 'value');
// 链式调用
$cache->set('user_id', 1001)->set('username', '张三');
获取缓存
// 获取缓存
$value = $cache->get('key');
// 判断缓存是否存在
if ($cache->has('key')) {
// 缓存存在
}
删除缓存
// 删除单个缓存
$cache->delete('key');
// 清空所有缓存
$cache->clear();
助手函数cache()使用方法
cache($name, $val, $expire = 3600)
//$name 缓存名称(注意命名唯一性,防止重复)
//$val 缓存值 $expire 缓存时间,默认3600秒
// 设置缓存
cache('user_profile_1001', $userData, 7200); // 缓存2小时
// 获取缓存
$userData = cache('user_profile_1001');
// 删除缓存
cache('user_profile_1001', false);
// 使用Redis驱动
cache('hot_products', $products, 1800, 'redis');