Gearman.class.php 2.96 KB
<?php
class Util_Server_Adapter_Clouds_Gearman implements Util_Server_Adapter_Interface {
	/**
	 * 配置节点段中的名称
	 *
	 * @var String
	 */
	const SECTION = 'gearman';
	/**
	 * 配置节点段中的字段
	 * 
	 * @var String
	 */
	const PRENAME = 'servers';
	
	/**
	 * 存放配置文件
	 * 
	 * @var String
	 */
	private $_config = '';
	
	/**
	 * 构造函数
	 */
	public function __construct($option = null) {
	    $this->_config = Util_Common_Core::loadGearman();
	}
	
	/**
	 * 获取均衡后的选择服务器列表
	 *
	 * @return array
	 */
	public function loadBalanceServer() {
	    $svrobj = Util_Common_Core::loadConfig ( $this->_config, self::SECTION );
		$servers = $this->_getServersFromString ( str_replace ( ' ', '', $svrobj->{self::PRENAME} ) );
		if (empty ( $servers )) {
			return false;
		}
		$return = $this->_getValidServer ( $servers );
		return $return;
	}
	
	/**
	 * 读取服务器列表
	 *
	 * @return array
	 */
	public function loadServers() {
		$svrobj = Util_Common_Core::loadConfig ( $this->_config, self::SECTION );
		$svrstring = str_replace ( ' ', '', $svrobj->{self::PRENAME} );
		return $this->_checkServer($svrstring);
	}
	
	/**
	 * 分析取得的服务器字符串,得到服务器配置数组
	 *
	 * @param string $svrstring
	 * @return array
	 */
	private function _getServersFromString($svrstring) {
        $tmpary = $this->_checkServer($svrstring);
		$return = array ();
		$counter = count ( $tmpary );
		for($i = 0; $i < $counter; $i ++) {
			if (($tmp = parse_url ( $tmpary [$i] )) !== false && $this->_checkSvrAry ( $tmp )) {
				$return [] = $tmpary [$i];
			}
		}
		return $return;
	}
	
	/**
	 * 得到有效的服务器,通过fsocket检测IP和端口
	 *
	 * @param array $servers
	 * @return array|false
	 */
	private function _getValidServer($servers) {
		$counter = count ( $servers );
		if (($rdm = rand ( 1, $counter )) && Util_Server_Adapter_CheckServer::check ( $servers [$rdm - 1] ['host'], $servers [$rdm - 1] ['port'] ) === true) {
			return $servers [$rdm - 1];
		} elseif (($rdm = rand ( 1, $counter )) && Util_Server_Adapter_CheckServer::check ( $servers [$rdm - 1] ['host'], $servers [$rdm - 1] ['port'] ) === true) {
			return $servers [$rdm - 1];
		} else {
			throw new Util_Server_Exception ( 'Gearman 服务器全挂了!' );
		}
	}
	
	/**
	 * 检查服务器配置
	 *
	 * @param string $svrstring
	 * @throws Util_Server_Exception
	 * @return void
	 */
	private function _checkServer($svrstring) {
		if ($svrstring == '') {
			throw new Util_Server_Exception ( __CLASS__ . ':服务器配置字符串为空!' );
		}
		$tmpary = array_unique ( explode ( ',', $svrstring ) );
		if (count ( $tmpary ) == 0) {
			throw new Util_Server_Exception ( __CLASS__ . ':服务器配置字符串格式错误!' );
		}
		return $tmpary;
	}
	
	/**
	 * 测试服务器配置数组是否格式正常
	 *
	 * @param array $ary
	 * @return boolean
	 */
	private function _checkSvrAry(array $ary) {
		return isset ( $ary ['host'] ) && isset ( $ary ['port'] );
	}
	}