PHP封装一个简单的单例模式Redis操作类

代码如下:

<?php

class DRedis {

    private $redis;
    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('127.0.0.1',6379);
        if($result === false) {
            throw new \Exception('redis connect error');
        }
    }

    public function setex($key, $value, $expire){
        return $this->redis->setex($key, $expire, $value);
    }

    public function setnx($key,$value){
        return $this->redis->setnx($key,$value);
    }

    public function seget($key){
        return $this->redis->get($key);
    }

    public function del($key){
        return $this->redis->del($key);
    }

    //其他操作省略......

    /**
     * 防止clone多个实例
     */
    private function __clone(){

    }

    /**
     * 防止反序列化
     */
    private function __wakeup(){

    }
}


    //调用示例
    // $redis = DRedis::getInstance()->setex('aaa',666,10);

    //测试
    // $redis1 = DRedis::getInstance();
    // $redis2 = DRedis::getInstance();
    // $redis3 = DRedis::getInstance();
    // var_dump($redis1);
    // echo '<hr>';
    // var_dump($redis2);
    // echo '<hr>';
    // var_dump($redis3);
发布了103 篇原创文章 · 获赞 167 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/msllws/article/details/100809471