当前位置:首页 > PHP

php实现缓存代码

2026-02-15 12:23:09PHP

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 是高性能的分布式内存对象缓存系统,适合高并发场景。

php实现缓存代码

$memcached = new Memcached();
$memcached->addServer('localhost', 11211);

// 设置缓存
$memcached->set('key', 'value', 3600);

// 获取缓存
$value = $memcached->get('key');
if ($memcached->getResultCode() == Memcached::RES_NOTFOUND) {
    // 缓存不存在
}

Redis 缓存

Redis 是更强大的键值存储系统,支持多种数据结构。

php实现缓存代码

$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);
        }
    }
}

标签: 缓存代码
分享给朋友:

相关文章

代码实现vue

代码实现vue

安装Vue.js 通过npm或yarn安装Vue.js最新稳定版本。确保已安装Node.js环境。 npm install vue # 或 yarn add vue 创建Vue实例 在HTML文件…

react如何代码优化

react如何代码优化

减少不必要的重新渲染 使用 React.memo 包装函数组件以避免在 props 未变化时重新渲染。对于类组件,可以通过 shouldComponentUpdate 或继承 PureComponen…

淘宝css代码制作

淘宝css代码制作

在淘宝店铺装修中,CSS代码用于自定义页面样式,提升视觉体验。以下是关键方法和注意事项: 自定义模块样式 通过淘宝旺铺的“自定义模块”功能,可以插入CSS代码。代码需包裹在<style>…

js实现轮播代码

js实现轮播代码

基础轮播实现 使用HTML、CSS和JavaScript创建一个简单的轮播效果。HTML部分定义轮播容器和图片元素。 <div class="carousel"> <div c…

vue实现弹窗代码

vue实现弹窗代码

Vue 弹窗实现方法 方法一:使用组件与v-if控制显示 创建一个独立的弹窗组件(如Modal.vue),通过父组件的v-if或v-show控制显隐: <!-- Modal.vue --…

vue实现网站代码

vue实现网站代码

Vue 实现网站代码的基本步骤 安装 Vue.js 通过 npm 或 CDN 引入 Vue.js。使用 npm 安装:npm install vue。或者直接在 HTML 文件中引入 Vue CDN:…