CheckServer.class.php 2.22 KB
<?php
class Util_Server_Adapter_CheckServer {

    /**
     * 存储Tracker延迟时间
     */
    const TIMEOUT = 15;

    /**
     * 服务器不好的情况下检查时间(5分钟)
     * 
     * @var Integer
     */
    private static $expire = 300;
    
    /**
     * 服务器好的情况下检查时间(20分钟)
     *
     * @var Integer
     */
    private static $goodExpire = 1200;

    /**
     * 检验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 Util_Server_Exception ('下列参数不合法: host:'.$host.' port:'.$port.' type:'.$type  );
        }
        $statusKeyName = 'check://'.$type.'_'.$host.'_'.$port.'_status';
        $lastModified = time();
        $key = $host.':'.$port;
        $apcObj = array();
        if ( Util_Cache_Adapter_Apc::isEnabled () ) {
            $apcObj = Util_Cache_Adapter_Apc::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 ( Util_Cache_Adapter_Apc::isEnabled () ) {
        	$apcObj = array();//清除值
			$apcObj[ $host.':'.$port ] = array (
                                        'status' => $status,
                                        'lastModified' => $lastModified
                                     );
			Util_Cache_Adapter_Apc::set ( $statusKeyName, new ArrayObject ( $apcObj ) );
		}
        return $status;
    }
}