探索 PHP 缓存技术:从文件缓存到 Memcached 实战

2025-12-10 31阅读

文章最后更新时间:2025年12月11日

在高并发场景下,频繁查询数据库会导致性能瓶颈,PHP 缓存技术能有效缓解这一问题 —— 通过将高频访问的数据存储在内存或文件中,减少数据库交互。本文讲解文件缓存和 Memcached 两种常用缓存方式。

php.jpg

一、基础:文件缓存实现(适合小量数据)

<?php
// 定义缓存函数
function getCache($key, $expire = 3600) {
    $cacheFile = './cache/' . md5($key) . '.txt';
    // 检查缓存是否存在且未过期
    if (file_exists($cacheFile) && (filemtime($cacheFile) + $expire) > time()) {
        return file_get_contents($cacheFile);
    }
    return false;
}

function setCache($key, $data) {
    $cacheDir = './cache/';
    if (!is_dir($cacheDir)) mkdir($cacheDir, 0755, true);
    $cacheFile = $cacheDir . md5($key) . '.txt';
    file_put_contents($cacheFile, $data);
}

// 使用缓存:获取文章列表
$cacheKey = 'article_list';
$articleList = getCache($cacheKey);
if (!$articleList) {
    // 缓存不存在,查询数据库
    $articleList = json_encode(['文章1', '文章2', '文章3']); // 模拟数据库查询结果
    // 设置缓存
    setCache($cacheKey, $articleList);
}
echo "文章列表:" . $articleList;
?>

二、进阶:Memcached 缓存(适合高频数据)

<?php
// 连接Memcached
$mem = new Memcached();
$mem->addServer('127.0.0.1', 11211); // 服务器地址+端口

// 设置缓存(有效期60秒)
$mem->set('user_info_1', json_encode(['name' => '张三', 'age' => 25]), 60);

// 获取缓存
$userInfo = $mem->get('user_info_1');
if ($userInfo) {
    echo "从缓存获取:" . $userInfo;
} else {
    // 缓存失效,查询数据库并重新设置缓存
    $userInfo = json_encode(['name' => '张三', 'age' => 25]);
    $mem->set('user_info_1', $userInfo, 60);
    echo "从数据库获取:" . $userInfo;
}

// 删除缓存
// $mem->delete('user_info_1');
?>

总结

文件缓存实现简单、无需额外服务,适合中小站点的低频数据缓存;Memcached 将数据存储在内存中,读取速度极快,适合高并发场景的高频数据(如用户信息、热门文章)。实际开发中可根据业务场景选择缓存方式,核心原则是 “缓存高频访问、低频修改的数据”,同时注意缓存过期时间,避免数据不一致。
文章版权声明:除非注明,否则均为Dark零点博客原创文章,转载或复制请以超链接形式并注明出处。