php实现缓存
PHP 缓存实现方法
文件缓存
文件缓存是最简单的缓存方式,将数据存储在文件中,适用于小型应用或临时数据存储。
// 写入缓存
function writeCache($key, $data, $ttl = 3600) {
$cacheFile = 'cache/' . md5($key) . '.cache';
$cacheData = [
'expires' => time() + $ttl,
'data' => $data
];
file_put_contents($cacheFile, serialize($cacheData));
}
// 读取缓存
function readCache($key) {
$cacheFile = 'cache/' . md5($key) . '.cache';
if (file_exists($cacheFile)) {
$cacheData = unserialize(file_get_contents($cacheFile));
if ($cacheData['expires'] > time()) {
return $cacheData['data'];
}
unlink($cacheFile);
}
return false;
}
Memcached 缓存
Memcached 是高性能的分布式内存对象缓存系统,适合大型应用。
$memcached = new Memcached();
$memcached->addServer('localhost', 11211);
// 设置缓存
$memcached->set('key', 'value', 3600);
// 获取缓存
$value = $memcached->get('key');
if ($value === false) {
// 缓存未命中处理
}
Redis 缓存
Redis 是更高级的键值存储系统,支持多种数据结构。
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
// 设置缓存
$redis->set('key', 'value');
$redis->expire('key', 3600);
// 获取缓存
$value = $redis->get('key');
if ($value === false) {
// 缓存未命中处理
}
OPcache
PHP 内置的 OPcache 可以缓存预编译的脚本字节码,提升 PHP 执行效率。
; php.ini 配置
[opcache]
opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
数据库查询缓存
对于频繁执行的数据库查询,可以使用查询缓存。
// 使用文件缓存存储查询结果
function cachedQuery($sql, $params = [], $ttl = 3600) {
$cacheKey = md5($sql . serialize($params));
$result = readCache($cacheKey);
if ($result === false) {
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
writeCache($cacheKey, $result, $ttl);
}
return $result;
}
页面缓存
对于静态内容或变化不频繁的页面,可以缓存整个页面输出。
ob_start();
// 页面内容生成
$content = ob_get_contents();
file_put_contents('cache/page.html', $content);
ob_end_flush();
缓存清除策略
合理的缓存清除策略对系统性能至关重要。

// 根据时间清除过期缓存
function clearExpiredCache($dir = 'cache/') {
$files = glob($dir . '*.cache');
$now = time();
foreach ($files as $file) {
$cacheData = unserialize(file_get_contents($file));
if ($cacheData['expires'] < $now) {
unlink($file);
}
}
}
// 手动清除特定缓存
function removeCache($key) {
$cacheFile = 'cache/' . md5($key) . '.cache';
if (file_exists($cacheFile)) {
unlink($cacheFile);
}
}
缓存最佳实践
- 为不同的数据类型设置合理的过期时间
- 使用命名空间或前缀区分不同模块的缓存
- 监控缓存命中率以优化缓存策略
- 考虑使用多级缓存架构
- 在高并发环境下注意缓存击穿问题
- 对敏感数据谨慎使用缓存
以上方法可以根据具体项目需求组合使用,以达到最佳性能优化效果。






