首页 > php教程 > PHP源码 > 正文

Redis Client,单例

PHP中文网
发布: 2016-05-23 17:10:17
原创
1674人浏览过

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);
	}
}

?>
登录后复制
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号