首页 > 其他 > 详细

Redis基础知识之——自定义封装单实例和普通类Redis

时间:2016-09-24 20:20:34      阅读:177      评论:0      收藏:0      [点我收藏+]

一、普通Redis实例化类:

class MyRedis
{
    private $redis;

    public function __construct($host = ‘121.41.88.209‘, $port = 63789)
    {
        $this->redis = new Redis();
        $this->redis->connect($host, $port);
    }

    public function expire($key = null, $time = 0)
    {
        return $this->redis->expire($key, $time);
    }

    public function psubscribe($patterns = array(), $callback)
    {
        $this->redis->psubscribe($patterns, $callback);
    }

    public function setOption()
    {
        $this->redis->setOption(\Redis::OPT_READ_TIMEOUT,-1);
    }

}

二、单例模式Redis实例化类:

<?php
/**
 * Created by PhpStorm.
 * User: Tinywan
 * Date: 2016/7/3
 * Time: 9:26
 * Mail: Overcome.wan@Gmail.com
 * Singleton instance
 */

namespace Org\Util;

class RedisInstance
{
    /**
     * 类对象实例数组,共有静态变量
     * @var null
     */
    private static $_instance;

    /**
     * 数据库连接资源句柄
     * @var
     */
    private static $_connectSource;

    /**
     * 私有化构造函数,防止类外实例化
     * RedisConnect constructor.
     */
    private function __construct()
    {

    }

    /**
     *  单例方法,用于访问实例的公共的静态方法
     * @return \Redis
     * @static
     */
    public static function getInstance()
    {
        if (!(static::$_instance instanceof \Redis)) {
            static::$_instance = new \Redis();
            self::getInstance()->connect(C(‘MASTER.HOST‘), C(‘MASTER.PORT‘), C(‘MASTER.TIMEOUT‘));
        }
        return static::$_instance;
    }

    /**
     * Redis数据库是否连接成功
     * @return bool|string
     */
    public static function connect()
    {
        // 如果连接资源不存在,则进行资源连接
        if (!self::$_connectSource)
        {
            //@return bool TRUE on success, FALSE on error.
            self::$_connectSource = self::getInstance()->connect(C(‘MASTER.HOST‘), C(‘MASTER.PORT‘), C(‘MASTER.TIMEOUT‘));
            // 没有资源返回
            if (!self::$_connectSource)
            {
                return ‘Redis Server Connection Fail‘;
            }
        }
        return self::$_connectSource;
    }

    /**
     * 私有化克隆函数,防止类外克隆对象
     */
    private function __clone()
    {
        // TODO: Implement __clone() method.
    }


    /**
     * @return \Redis
     * @static
     */
    public static function test()
    {
        return ‘test‘;
    }

 

Redis基础知识之——自定义封装单实例和普通类Redis

原文:http://www.cnblogs.com/tinywan/p/5903919.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!