CheckServer.php 1.9 KB
<?php
class Q_Server_CheckServer {
	
	/**
	 * 存储Tracker延迟时间
	 */
	const TIMEOUT = 15;
	
	/**
	 * 服务器不好的情况下检查时间(5分钟)
	 *
	 * @var Integer
	 */
	private static $expire = 5;
	
	/**
	 * 服务器好的情况下检查时间(20分钟)
	 *
	 * @var Integer
	 */
	private static $goodExpire = 10;
	
	/**
	 * 检验Server
	 *
	 * @param String $host        	
	 * @param Integer $port        	
	 * @param String $type        	
	 * @return bool
	 */
	public static function check($host, $port = '3306', $type = 'db') {
		if (empty ( $host ) || empty ( $port ) || empty ( $type )) {
			throw new Q_Server_Exception ( '下列参数不合法: host:' . $host . ' port:' . $port . ' type:' . $type );
		}
		$statusKeyName = 'check://' . $type . '_' . $host . '_' . $port . '_status';
		$lastModified = time ();
		$key = $host . ':' . $port;
		$apcObj = array ();
		if (Q_Cache_Backend::isEnabled ()) {
			$apcObj = Q_Cache_Backend::get ( $statusKeyName );
			// 务器状态为true
			if (! empty ( $apcObj [$key] ) && $apcObj [$key] ['status'] == true && ($lastModified - $apcObj [$key] ['lastModified']) <= self::$goodExpire) {
				return $apcObj [$key] ['status'];
			}
			// 务器状态为false
			if (! empty ( $apcObj [$key] ) && $apcObj [$key] ['status'] == false && ($lastModified - $apcObj [$key] ['lastModified']) <= self::$expire) {
				return $apcObj [$key] ['status'];
			}
			if (empty ( $apcObj )) {
				$apcObj = array ();
			}
		}
		
		$errno = 0;
		$errstr = '';
		$status = true;
		$fs = @fsockopen ( $host, $port, $errno, $errstr, self::TIMEOUT );
		if (! $fs) {
			@fclose ( $fs );
			$status = false;
		}
		if (Q_Cache_Backend::isEnabled ()) {
			$apcObj = array (); // 清除值
			$apcObj [$host . ':' . $port] = array (
					'status' => $status,
					'lastModified' => $lastModified 
			);
			Q_Cache_Backend::set ( $statusKeyName, new ArrayObject ( $apcObj ) );
		}
		return $status;
	}
}