想了两种解决方式都不太理想:
第一种是尝试远程链接线上数据库
来判断
第二种是curl请求
线上服务器的一个接口,
但是这两种方式,等待回应的时间过长,请问如何在1~2s时间内判断线上服务器是否宕机(开启)?
(判断完之后,根据结果进行相应的操作,进行后续操作的时候,需要先判断服务器是否开启。)
做TCP层的心跳检测,定时去发送数据包来判断线上服务器是否宕机。
$this->ftp = stream_socket_client( $remote, $errno, $errstr, $this->connection_timeout, STREAM_CLIENT_CONNECT, $this->context ); if (false === $this->ftp) { // 连接失败 throw new RuntimeException( sprintf( 'Error Connecting to server(%s): %s ', $errno, $errstr ), $errno ); }
你可以直接 Ping 一下。调用一下 shell 。
if(fopen= (url,'r'))
echo '我没有挂';
可以用fsockopen
$ip = '192.168.1.1';
$port = 80;
$timeout = 2;
$sock = @fsockopen($ip, $port, $errno, $errmsg, $timeout);
if($sock) {
//todo: server is online
}else {
//todo: server is offline
}
防止意外的超时,可以做个循环
$count = 3; //尝试次数
$flag = false; //状态标记
$ip = '192.168.1.1';
$port = 80;
$timeout = 2;
while($count--) {
$sock = @fsockopen($ip, $port, $errno, $errmsg, $timeout);
if($sock) {
fclose($sock);
$flag = true;
break;
}
}
if ($flag) {
//你的业务逻辑
} else {
echo "$errmsg ($errno)<br />" . PHP_EOL;
}