美文网首页
PHP Redis使用单例模式

PHP Redis使用单例模式

作者: HueyYao | 来源:发表于2020-12-26 18:02 被阅读0次

PHP redis使用单例模式

单例模式的使用可以很好的节省资源 在频繁调用get和set时是很好的选择

使用场景:验证码登录功能

namespace app\common\lib\redis;
class Predis {
    public $redis = "";
    /**
     * 定义单例模式的变量
     * @var null
     */
    private static $_instance = null;

    public static function getInstance() {
        if(empty(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    private function __construct() {
        $this->redis = new \Redis();
        $result = $this->redis->connect(config('redis.host'), config('redis.port'), config('redis.timeOut'));
        if($result === false) {
            throw new \Exception('redis connect error');
        }
    }
}

相关文章

网友评论

      本文标题:PHP Redis使用单例模式

      本文链接:https://www.haomeiwen.com/subject/xuvgnktx.html