Redis的页面缓存、对象缓存、查询结果缓存

1. 页面缓存

目标:缓存整个页面的输出内容,以提高响应速度,减少服务器资源消耗。

实现步骤

  • 在页面请求开始时,检查缓存中是否已有该页面的缓存内容。
  • 如果有缓存,直接输出缓存内容并结束请求。
  • 如果没有缓存,生成页面内容并将其存入缓存,同时返回给用户。

代码示例

<?php
function cachePage($cacheKey, $expire = 300) {
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);

    // 检查缓存
    $cachedContent = $redis->get($cacheKey);
    if ($cachedContent) {
        echo $cachedContent;
        exit();
    }

    // 开启输出缓冲
    ob_start();

    // 动态生成页面内容
    echo "<html><body>这是动态生成的页面内容</body></html>";

    // 获取输出缓冲的内容
    $content = ob_get_contents();

    // 将内容缓存到Redis
    $redis->setex($cacheKey, $expire, $content);

    // 关闭输出缓冲并输出内容
    ob_end_flush();
}

// 使用缓存函数
cachePage('homepage_cache', 300);

2. 对象缓存

目标:将频繁访问的对象(如用户信息、商品信息)缓存到Redis中,减少数据库查询。

实现步骤

  • 在获取对象数据时,首先检查缓存是否存在。
  • 如果存在缓存,则直接返回缓存的数据。
  • 如果不存在缓存,则查询数据库,并将查询结果缓存到Redis中。

代码示例

<?php
function getUserInfo($userId) {
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);

    $cacheKey = "user_info_" . $userId;

    // 尝试从缓存中获取数据
    $userInfo = $redis->get($cacheKey);
    if ($userInfo) {
        return json_decode($userInfo, true);
    }

    // 如果缓存中没有,查询数据库
    $db = new mysqli('localhost', 'username', 'password', 'database');
    $result = $db->query("SELECT * FROM users WHERE id = " . intval($userId));
    $userInfo = $result->fetch_assoc();

    // 将查询结果缓存到Redis
    if ($userInfo) {
        $redis->setex($cacheKey, 600, json_encode($userInfo));
    }

    return $userInfo;
}

// 获取用户信息
$userInfo = getUserInfo(123);
print_r($userInfo);

3. 查询结果缓存

目标:将复杂的查询结果缓存到Redis中,避免重复计算,提高系统性能。

实现步骤

  • 执行复杂查询前,检查缓存中是否已有该查询结果。
  • 如果有缓存,则直接返回缓存数据。
  • 如果没有缓存,执行查询,并将结果缓存到Redis中。

代码示例

<?php
function getProductList() {
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);

    $cacheKey = "product_list";

    // 检查缓存中是否已有查询结果
    $cachedResult = $redis->get($cacheKey);
    if ($cachedResult) {
        return json_decode($cachedResult, true);
    }

    // 如果没有缓存,执行复杂查询
    $db = new mysqli('localhost', 'username', 'password', 'database');
    $result = $db->query("SELECT * FROM products WHERE category_id = 1 AND price > 100 ORDER BY price DESC");
    
    $productList = [];
    while ($row = $result->fetch_assoc()) {
        $productList[] = $row;
    }

    // 将查询结果缓存到Redis
    $redis->setex($cacheKey, 300, json_encode($productList));

    return $productList;
}

// 获取产品列表
$productList = getProductList();
print_r($productList);

通过结合 Redis 和 MySQL,可以显著提高 PHP 应用的性能。页面缓存适用于静态或不频繁变化的页面,对象缓存适用于频繁访问的对象数据,而查询结果缓存则能减少复杂查询的执行频率。各类缓存的生命周期应根据具体业务需求进行调整,以达到最佳的性能优化效果。

 

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值