php教程 PHP源码 Redis Client,单例

Redis Client,单例

May 23, 2016 pm 05:10 PM

php代码

<?php  //if(!defined('BASEPATH')) exit('No direct script access allowed...');

/**
 * ---------------- redis.conf.php ------------------
 * $redis_conf = array();
 * $redis_conf['master'] = array();;
 * $redis_conf['master']['host'] = '127.0.0.1';
 * $redis_conf['master']['port'] = 6379;
 * $redis_conf['master']['passwd'] = '';
 * $redis_conf['master']['timeout'] = 1;
 * ---------------- author:  simon ------------------
 */

/**
 * Redis Client Interface
 *
 * ------------------- Usage ---------------------
 * $conf_dir = __DIR__ .'/../conf/redis.conf.php';
 * $redis = RedisCli::getInstance($conf_dir, 'master');
 * $ret = $redis->set('xxxxx', 'good');
 * $ret = $redis->get('xxxxx');
 *
 */

class RedisCli {
	private static $_instance = array();
	private $_redis = false;
	
	/**
	 * 单例模型,构造函数
	 */
	public static function getInstance($conf_dir='/xxx/redis.conf.php', $serverName='master') {
		if (isset(self::$_instance[$serverName])) {
			return self::$_instance[$serverName];
		}
		require_once($conf_dir);
		if (!isset($redis_conf[$serverName])) {
			throw new Exception("param serverName Or redis config error...");
		}
		$conf = $redis_conf[$serverName];
		if (!class_exists('Redis')) {
			throw new Exception("Class Redis not exists, please install the php Redis extension...");
		}
		if (isset($conf['host']) && isset($conf['port']) && isset($conf['passwd']) && isset($conf['timeout'])) {
			self::$_instance[$serverName] = new self($conf['host'], $conf['port'], $conf['passwd'], $conf['timeout']);
			return self::$_instance[$serverName];
		}
		return false;
	}

	/**
	 *  私有, 单例模型,禁止外部构造
	 */
	private function __construct($host, $port, $passwd, $timeout) {
		$this->_redis = new Redis();
		if ($this->_redis->connect($host, $port, $timeout)) {
			if (!empty($passwd)) {
				$this->_redis->auth($passwd);
			}
		}
	}

	/**
	 *  私有, 单例模型,禁止克隆
	 */
	private function __clone() {
	}

    /**
	 *  公有,调用对象函数
	 */
	public function __call($method, $args) {
		if (!$this->_redis || !$method) {
			return false;
		}
		if (!method_exists($this->_redis, $method)) {
			throw new Exception("Class RedisCli not have method ($method) ");
		}
		return call_user_func_array(array($this->_redis, $method), $args);
	}
}

?>
로그인 후 복사
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

뜨거운 기사 태그

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)