php实现缓存
PHP 实现缓存的常见方法
文件缓存
文件缓存是最简单的缓存方式,将数据序列化后存储到文件中。适合小型项目或临时数据存储。
$cacheFile = 'cache/data.cache';
$cacheTime = 3600; // 1小时
// 读取缓存
if (file_exists($cacheFile) && time() - filemtime($cacheFile) < $cacheTime) {
$data = unserialize(file_get_contents($cacheFile));
} else {
$data = getDataFromDatabase(); // 获取数据的函数
file_put_contents($cacheFile, serialize($data));
}
Memcached
Memcached 是高性能的分布式内存对象缓存系统,适合大规模数据缓存。
$memcached = new Memcached();
$memcached->addServer('localhost', 11211);
$key = 'user_data';
$data = $memcached->get($key);
if (!$data) {
$data = getDataFromDatabase();
$memcached->set($key, $data, 3600); // 缓存1小时
}
Redis
Redis 是更高级的键值存储系统,支持多种数据结构,性能优异。
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$key = 'product_list';
if (!$redis->exists($key)) {
$data = getProductsFromDB();
$redis->set($key, json_encode($data));
$redis->expire($key, 1800); // 30分钟过期
} else {
$data = json_decode($redis->get($key));
}
APC/OPcache
APC (Alternative PHP Cache) 和 OPcache 是PHP内置的字节码缓存,可显著提升PHP性能。
if (function_exists('apc_store')) {
$key = 'system_config';
if (!apc_exists($key)) {
$data = loadConfig();
apc_store($key, $data, 86400); // 缓存24小时
}
$config = apc_fetch($key);
}
数据库查询缓存
对于MySQL等数据库,可以启用查询缓存或使用ORM的缓存功能。
// PDO示例
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
$stmt = $pdo->prepare("SELECT SQL_CACHE * FROM users WHERE id = ?");
$stmt->execute([$userId]);
浏览器缓存控制
通过HTTP头控制浏览器缓存,减少服务器负载。
header("Cache-Control: max-age=3600, public");
header("Expires: ".gmdate('D, d M Y H:i:s', time()+3600).' GMT');
缓存策略建议
- 对于频繁读取但很少变更的数据使用长期缓存
- 设置合理的缓存过期时间
- 重要数据变更时及时清除相关缓存
- 考虑使用标签化缓存管理相关数据组
- 高并发系统建议使用内存缓存而非文件缓存
每种缓存方式各有优劣,应根据项目规模、性能需求和技术栈选择最合适的方案或组合使用多种缓存策略。







