php实现缓存
PHP实现缓存的常见方法
文件缓存
将数据序列化后存储到文件中,适用于小型项目或简单的缓存需求。使用file_put_contents和file_get_contents函数实现。
$cacheFile = 'cache/data.cache';
$data = ['key' => 'value'];
// 写入缓存
if (!file_exists('cache')) {
mkdir('cache', 0777, true);
}
file_put_contents($cacheFile, serialize($data));
// 读取缓存
if (file_exists($cacheFile)) {
$cachedData = unserialize(file_get_contents($cacheFile));
}
Memcached扩展
高性能分布式内存对象缓存系统,适合大规模应用。需要安装Memcached服务并启用PHP扩展。
$memcached = new Memcached();
$memcached->addServer('localhost', 11211);
// 设置缓存
$memcached->set('key', 'value', 3600);
// 获取缓存
$value = $memcached->get('key');
Redis缓存
开源的内存数据结构存储,支持更复杂的数据类型。需要安装Redis服务和PHP Redis扩展。
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
// 字符串缓存
$redis->set('key', 'value');
$redis->expire('key', 3600);
// 哈希缓存
$redis->hSet('user', 'name', 'John');
$redis->hSet('user', 'age', 30);
APC/OPcache
PHP内置的字节码缓存,可显著提高PHP性能。PHP 5.5+版本内置OPcache。
// APC缓存示例
apc_store('key', 'value', 3600);
$value = apc_fetch('key');
// OPcache自动缓存编译后的脚本
// 需在php.ini中启用
数据库缓存
使用数据库表存储缓存数据,适合需要持久化的场景。
// 创建缓存表
CREATE TABLE cache (
id VARCHAR(255) PRIMARY KEY,
data LONGTEXT,
expires INT
);
// 使用PDO操作缓存
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$stmt = $pdo->prepare("REPLACE INTO cache (id, data, expires) VALUES (?, ?, ?)");
$stmt->execute(['key', serialize($data), time() + 3600]);
缓存策略实现
设置缓存过期时间,避免数据过期:
function getWithCache($key, $callback, $ttl = 3600) {
$cacheFile = "cache/".md5($key);
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $ttl) {
return unserialize(file_get_contents($cacheFile));
}
$data = $callback();
file_put_contents($cacheFile, serialize($data));
return $data;
}
缓存清除机制
定期清理过期缓存文件:

function clearExpiredCache($dir, $maxLifetime) {
$files = glob($dir."/*");
$now = time();
foreach ($files as $file) {
if (is_file($file) && ($now - filemtime($file)) >= $maxLifetime) {
unlink($file);
}
}
}
注意事项
- 敏感数据不应缓存
- 缓存键名应唯一且有描述性
- 高并发场景考虑使用锁机制
- 监控缓存命中率优化策略
- 分布式系统需考虑缓存一致性






