PHP+Redis实例 页面缓存

Posted by thinkwei on January 7, 2021
    
首先,需要安装redis,步骤如下(windows环境下):
1. 进入 DOS窗口

2. 在进入Redis的安装目录

3. 输入:redis-server --service-install redis.windows.conf --loglevel verbose ( 安装redis服务 )

4.  输入:redis-server --service-start ( 启动服务 )

5. 输入:redis-server --service-stop (停止服务)

启动指定的配置文件redis-server --service-start redis.windows-service.conf

其次,在phpinfo.php里面有没有redis相关的扩展,如果没有的话还需要安装或者开启。

调用实例如下:
实例一:
   
<?php
class Test
{
    public $redis = null;

    public function __construct()
    {
        $this->redis = new Redis();
        $this->redis->connect('127.0.0.1',6379);
        $this->redis->auth('');
    }
    //这里是个例子模型,按照自己的用法去套进去就行
    //以文章为例子吧
    //页面级,接口级都可以用
    public function getData()
    {
        //判断缓存的键是否还存在
        if(!$this->redis->exists("cache:".$commentid))
        {
            //缓存不存在
            //下面的get_mysql_data()函数只是个例子,按照自己具体情况去mysql获取数据
            $data = $this->get_mysql_data();
            $json = json_encode($data,JSON_UNESCAPED_UNICODE);
            //存入redis
            $this->redis->set("cache:".$commentid,$json);
            //设置过期时间5分钟
            $this->redis->expire("cache:".$commentid,60*60*5);
        }

        $json = $this->redis->get("cache:".$commentid);
        $data = json_decode($json,true);
        return $data;
    }
}

实例二:

部分内容摘自网络:https://www.cnblogs.com/fps2tao/p/9050001.html