php实现缓存代码
PHP 缓存实现方法
文件缓存
文件缓存是最简单的缓存方式,将数据存储在文件中,适合小型应用或临时缓存需求。
// 写入缓存
function setCache($key, $data, $expire = 3600) {
$file = 'cache/' . md5($key) . '.cache';
$content = [
'expire' => time() + $expire,
'data' => $data
];
file_put_contents($file, serialize($content));
}
// 读取缓存
function getCache($key) {
$file = 'cache/' . md5($key) . '.cache';
if (!file_exists($file)) return false;
$content = unserialize(file_get_contents($file));
if (time() > $content['expire']) {
unlink($file);
return false;
}
return $content['data'];
}
Memcached 缓存
Memcached 是高性能的分布式内存对象缓存系统,适合高并发场景。

$memcached = new Memcached();
$memcached->addServer('localhost', 11211);
// 设置缓存
$memcached->set('key', 'value', 3600);
// 获取缓存
$value = $memcached->get('key');
if ($memcached->getResultCode() == Memcached::RES_NOTFOUND) {
// 缓存不存在
}
Redis 缓存
Redis 是更强大的键值存储系统,支持多种数据结构。

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
// 设置缓存
$redis->set('key', 'value', ['ex' => 3600]);
// 获取缓存
$value = $redis->get('key');
if ($value === false) {
// 缓存不存在或已过期
}
OPcache 缓存
OPcache 是 PHP 内置的字节码缓存,可显著提升 PHP 执行速度。
// 检查 OPcache 是否启用
if (function_exists('opcache_get_status')) {
$status = opcache_get_status();
if ($status['opcache_enabled']) {
// OPcache 已启用
}
}
数据库查询缓存
对于频繁查询的数据库结果可以缓存,减少数据库压力。
function queryWithCache($sql, $expire = 300) {
$cacheKey = md5($sql);
$cachedResult = getCache($cacheKey);
if ($cachedResult !== false) {
return $cachedResult;
}
$result = $db->query($sql)->fetchAll();
setCache($cacheKey, $result, $expire);
return $result;
}
缓存策略建议
- 根据应用规模选择合适的缓存方案
- 设置合理的过期时间,避免数据过期
- 考虑使用缓存命名空间,便于管理
- 实现缓存清除机制,保持数据一致性
- 监控缓存命中率,优化缓存策略
缓存清除方法
// 清除特定缓存
function clearCache($key) {
$file = 'cache/' . md5($key) . '.cache';
if (file_exists($file)) {
unlink($file);
}
}
// 清除所有缓存
function clearAllCache() {
$files = glob('cache/*.cache');
foreach ($files as $file) {
if (is_file($file)) {
unlink($file);
}
}
}






