缓存是提升ThinkPHP应用性能的关键手段,通过减少数据库查询、模板解析等耗时操作,显著加快页面响应速度。ThinkPHP提供了灵活的缓存机制,支持多种驱动、标签管理及事件监听,开发者需根据业务场景选择合适的策略。
ThinkPHP支持多种缓存方式,各有优缺点及适用场景:
cache(true)或cache('cache_name', 60)开启,减少重复查询;适合频繁访问且变化较少的数据。缓存配置主要在config/cache.php中进行,关键参数包括:
default为redis、memcached或file,决定全局缓存行为。host(127.0.0.1)、port(6379)、password(空或密码)、expire(默认过期时间,如3600秒);Memcached的host、port(11211);文件缓存的path(runtime_path() . ‘cache’)。strategy(LRU最近最少使用、LFU最不经常使用),优化内存使用效率。通过Cache门面实现缓存的设置、获取与删除:
use think\facade\Cache; // 设置缓存(键'article_list',值$dbResult,过期时间3600秒) Cache::set('article_list', $dbResult, 3600); // 获取缓存(若键不存在返回null) $list = Cache::get('article_list'); // 获取缓存(若键不存在返回默认值) $list = Cache::get('article_list', []); // 删除缓存 Cache::rm('article_list'); 缓存标签用于批量管理一组缓存,适合关联数据的批量更新:
// 设置带标签的缓存(键'article_1',值$detail,标签'content') Cache::set('article_1', $detail, 3600, ['content']); // 获取带标签的缓存键列表 $keys = Cache::tags('content')->getKeys(); // 删除带标签的所有缓存 Cache::tags('content')->rm(); 通过监听缓存事件(命中、未命中、删除),可实现日志记录、数据同步等功能:
use think\cache\driver\File; // 监听缓存命中事件 File::listen('hit', function ($key) { echo "缓存命中:{$key}"; }); // 监听缓存未命中事件 File::listen('miss', function ($key) { echo "缓存未命中:{$key}"; }); // 监听缓存删除事件 File::listen('rm', function ($key) { echo "缓存删除:{$key}"; }); 数据一致性是缓存使用的核心挑战,需通过以下方式保证:
// 文章更新后清除列表缓存 Db::name('article')->update($data); Cache::rm('article_list'); // 设置文章缓存时添加'content'标签 Cache::set('article_1', $detail, 3600, ['content']); // 文章分类更新后,清除'content'标签下所有缓存 Cache::tags('content')->rm(); maxmemory(Redis)或memory_limit(Memcached)限制内存占用。