当前位置:Gxlcms > PHP教程 > redis操作类(支持主从)

redis操作类(支持主从)

时间:2021-07-01 10:21:17 帮助过:8人阅读

基本配置文件:

 array('127.0.0.1',6379),
	'slaver'  => array('127.0.0.1',6379)
);

?>

操作类:

_serverConfig = $defaultConfig;
	}	

	private function createRedisInstance($config = array()) {
		if (count($config) < 2) {
			throw new Exception(strtr('Config invalid', array()));
		}
		$redis = new Redis();
		$redis->connect($config[0], $config[1]);
		return $redis;
	}	
	
	public function getRedisMaster() {
		if ($this->_redisMaster === null) {
			$this->_redisMaster = $this->createRedisInstance($this->_serverConfig[self::RD_MASTER]) ;			
		}
		return $this->_redisMaster;
	}

	public function getRedisSlave() {
		if ($this->_redisSlaver === null) {
			$this->_redisSlaver = $this->createRedisInstance($this->_serverConfig[self::RD_SLAVER]) ;			
		}
		return $this->_redisSlaver;
	}
	
	public function get($key, $master = false) {
		if(empty($key)) {
			return false;
		}
		$func = is_array($key) ? 'mGet' : 'get';
		if($master) {
			$redis = $this->getRedisMaster();
		}else{
			$redis = $this->getRedisSlave();
		}
		if(!$redis) {
			return false;
		}
		$value = $redis->$func($key);
		if($value === false) {			
			return false;
		}
		return $value;
	}

	public function set($key, $value, $expire = 0) {
		if(empty($key)) {			
			return false;
		}
		$redis = $this->getRedisMaster();		
		if(!$redis) {
			return false;
		}
		if($expire) {
			$ret = $redis->setex($key, $expire, $value);
		}
		else {
			$ret = $redis->set($key, $value);
		}
		if($ret === false) {
			return false;
		}
		return $ret;
	}

    
    /**
     * 条件形式设置缓存,如果 key 不存时就设置,存在时设置失败
     *
     * @param string $key 缓存KEY
     * @param string $value 缓存值
     * @return boolean
     */
	public function setnx($key, $value){
        return $this->getRedisMaster()->setnx($key, $value);
    }
       
    /**
     * 删除缓存
     *
     * @param string || array $key 缓存KEY,支持单个健:"key1" 或多个健:array('key1','key2')
     * @return int 删除的健的数量
     */
	 public function remove($key){
		return $this->getRedisMaster()->delete($key);
    }
       
    public function __call($name,$value) {
		/**
		 * 读写分离
		 */
		$redisWrite = array('zAdd','zRem','hIncrBy','info','rename', 'rpush', 'lpop','hMset', 'sadd', 'srem', 'incr', 'spop');
		$redisRead = array('zCard','zRank','zrevRank','zRevRange','hLen','hKeys','hVals','zRange','hMget','hGetAll', 'lrange', 'llen','mGet', 'smembers', 'sismember', 'scard', 'keys');
		if(in_array($name,$redisWrite)) { //master
			$redis = $this->getRedisMaster();
			return call_user_func_array(array($redis,$name),$value);
		}
		elseif(in_array($name,$redisRead)) { //slave		
			$redis = $this->_getRedisSlave();
			return call_user_func_array(array($redis,$name),$value);
		}
	}
}

?>

以上就介绍了redis操作类(支持主从),包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

人气教程排行