search
HomeBackend DevelopmentPHP TutorialPHP uses redis as cache (efficient technology)

PHP uses redis as cache (efficient technology)

高效PHP Redis缓存技术,可参考下步骤

是否想过PHP使用redis作为缓存时,如何能:

● 前后台模块共用Model层;

● 但是,不能每个Model类都进行缓存,这样太浪费Redis资源;

● 前后台模块可以自由决定从数据库还是从缓存读数据;

● 没有冗余代码;

● 使用方便。

● 这里我们先展示实现的最终效果。

最终的代码和使用说明请移步Github:

https://github.com/yeszao/php-redis-cache。

马上安装使用命令:

$ composer install yeszao/cache

 

经过简单配置就可以使用,请参看Github的README说明。

1 最终效果

假设在MVC框架中,model层有一个Book类和一个getById方法,如下:

class Book
{
    public function getById($id)
    {
        return $id;
    }
}

 

加入缓存技术之后,原来方法的调用方式和返回的数据结构都不应该改变。

所以,我们希望,最后的效果应该是这样的:

(new Book)->getById(100);           // 原始的、不用缓存的调用方式,还是原来的方式,一般是读取数据库的数据。
(new Book)->getByIdCache(100);      // 使用缓存的调用方式,缓存键名为:app_models_book:getbyid: + md5(参数列表)
(new Book)->getByIdClear(100);      // 删除这个缓存
(new Book)->getByIdFlush();         // 删除 getById() 方法对应的所有缓存,即删除 app_models_book:getbyid:*。这个方法不需要参数。

 

这样我们可以很清楚的明白自己在做什么,同时又知道数据的来源函数,并且被引用方式完全统一,可谓一箭三雕。

其实实现起来也比较简单,就是使用PHP的魔术方法__call()方法。

2 __call()方法

这里简单说明一下__call方法的作用。

在PHP中,当我们访问一个不存在的类方法时,就会调用这个类的__call()方法。

(如果类方法不存在,又没有写__call()方法,PHP会直接报错)

假设我们有一个Book类:

class Book
{
    public function __call($name, $arguments)
    {
        echo '类Book不存在方法', $name, PHP_EOL;
    }

    public function getById($id)
    {
        echo '我的ID是', $id, PHP_EOL;
    }
}

 

当调用存在的getById(50)方法时,程序打印:我的ID是50。

而如果调用不存在的getAge()方法时,程序就会执行到A类的__call()方法里面,这里会打印:类Book不存在方法getAge。

这就是__call的原理。

3 实现细节

接下来我们就利用__call()方法的这种特性,来实现缓存策略。

从上面的例子,我们看到,__call()方法被调用时,会传入两个参数。

name:想要调用的方法名arguments:参数列表

我们就可以在参数上面做文章。

还是以Book类为例,我们假设其原本结构如下:

class Book
{
    public function __call($name, $arguments)
    {
        // 待填充内容
    }

    public function getById($id)
    {
        return ['id' => $id, 'title' => 'PHP缓存技术' . $id];
    }
}

 

开始之前,我们还确认Redis的连接,这是缓存必须用到的,这里我们写个简单的单例类:

class Common
{
    private static $redis = null;

    public static function redis()
    {
        if (self::$redis === null) {
            self::$redis = new \Redis('127.0.0.1');
            self::$redis->connect('redis');
        }
        return self::$redis;
}

 

然后,我们开始填充__call()方法代码,具体说明请看注释:

class Book
{
    public function __call($name, $arguments)
    {
        // 因为我们主要是根据方法名的后缀决定具体操作,
        // 所以如果传入的 $name 长度小于5,可以直接报错
        if (strlen($name) < 5) {
            exit(&#39;Method does not exist.&#39;);
        }

        // 接着,我们截取 $name,获取原方法和要执行的动作,
        // 是cache、clear还是flush,这里我们取了个巧,动作
        // 的名称都是5个字符,这样截取就非常高效。
        $method = substr($name, 0, -5);
        $action = substr($name, -5);

        // 当前调用的类名称,包括命名空间的名称
        $class = get_class();

        // 生成缓存键名,$arguments稍后再加上
        $key = sprintf(&#39;%s:%s:&#39;, str_replace(&#39;\\&#39;, &#39;_&#39;, $class), $method);
        // 都用小写好看点
        $key = strtolower($key);

        switch ($action) {
            case &#39;Cache&#39;:
                // 缓存键名加上$arguments
                $key = $key . md5(json_encode($arguments));

                // 从Redis中读取数据
                $data = Common::redis()->get($key);

                // 如果Redis中有数据
                if ($data !== false) {
                    $decodeData = json_decode($data, JSON_UNESCAPED_UNICODE);
                    // 如果不是JSON格式的数据,直接返回,否则返回json解析后的数据
                    return $decodeData === null ? $data : $decodeData;
                }

                // 如果Redis中没有数据则继续往下执行

                // 如果原方法不存在
                if (method_exists($this, $method) === false) {
                    exit(&#39;Method does not exist.&#39;);
                }

                // 调用原方法获取数据
                $data = call_user_func_array([$this, $method], $arguments);

                // 保存数据到Redis中以便下次使用
                Common::redis()->set($key, json_encode($data), 3600);

                // 结束执行并返回数据
                return $data;
                break;

            case &#39;Clear&#39;:
                // 缓存键名加上$arguments
                $key = $key . md5(json_encode($arguments));
                return Common::redis()->del($key);
                break;

            case &#39;Flush&#39;:
                $key = $key . &#39;*&#39;;

                // 获取所有符合 $class:$method:* 规则的缓存键名 
                $keys = Common::redis()->keys($key);
                return Common::redis()->del($keys);
                break;

            default:
                exit(&#39;Method does not exist.&#39;);
        }
    }

    // 其他方法
}

 

这样就实现了我们开始时的效果。

4 实际使用时

在实际使用中,我们需要做一些改变,把这一段代码归入一个类中,

然后在model层的基类中引用这个类,再传入Redis句柄、类对象、方法名和参数,

这样可以降低代码的耦合,使用起来也更灵活。

完整的代码已经放在Github上,请参考文章开头的参考地址。

更多相关php知识,请访问php教程

The above is the detailed content of PHP uses redis as cache (efficient technology). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:cnblogs. If there is any infringement, please contact admin@php.cn delete
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)