背景与重试思路
公司内部众多服务依赖Curl或Soap协议与第三方系统交互数据。近期新增一项需求:当第三方服务发布版本导致无法连接其服务器时,系统应执行重试逻辑;而对于其他原因引发的业务处理失败,则按失败流程处理,不再重复调用。
核心思路在于区分异常类型。当检测到Curl或Soap因无法连接对方服务器而报错时,主动抛出TimeoutException异常,并在捕获该异常后触发重试机制;对于由其他错误导致的Exception,则视为最终失败,不进行重试。
Curl方式处理
针对Curl方式的超时与连接问题处理方案如下。
$ch = curl_init($url);
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5, //5秒连接时间
CURLOPT_TIMEOUT => 30, //30秒请求等待时间
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
if ($no = curl_errno($ch)) {
$error = curl_error($ch);
curl_close($ch);
//$no错误码7为连接不上,28为连接上了但请求返回结果超时
if(in_array(intval($no), [7, 28], true)) {
throw new TimeoutException('连接或请求超时' . $error, $no);
}
}
curl_close($ch);
Soap方式处理与源码分析
针对Soap方式的超时与连接问题处理方案如下。
PHP官方文档并未详细说明Soap在超时或连接失败时返回的具体代码。通常情况下,无论是业务处理失败还是连接中断等所有不成功的情况,都会抛出一个SoapFault异常。但通过查阅PHP源码,可以发现其中存在明确的定义。
相关定义位于PHP源文件 /ext/soap/php_http.c 中。
具体的错误代码定义内容如下所示。
add_soap_fault(this_ptr, "HTTP", "Unable to parse URL", NULL, NULL); add_soap_fault(this_ptr, "HTTP", "Unknown protocol. Only http and https are allowed.", NULL, NULL); add_soap_fault(this_ptr, "HTTP", "SSL support is not available in this build", NULL, NULL); add_soap_fault(this_ptr, "HTTP", "Could not connect to host", NULL, NULL); add_soap_fault(this_ptr, "HTTP", "Failed Sending HTTP SOAP request", NULL, NULL); add_soap_fault(this_ptr, "HTTP", "Failed to create stream??", NULL, NULL); add_soap_fault(this_ptr, "HTTP", "Error Fetching http headers", NULL, NULL); add_soap_fault(this_ptr, "HTTP", "Error Fetching http body, No Content-Length, connection closed or chunked data", NULL, NULL); add_soap_fault(this_ptr, "HTTP", "Redirection limit reached, aborting", NULL, NULL); add_soap_fault(this_ptr, "HTTP", "Didn't receive an xml document", NULL, err); add_soap_fault(this_ptr, "HTTP", "Unknown Content-Encoding", NULL, NULL); add_soap_fault(this_ptr, "HTTP", "Can't uncompress compressed response", NULL, NULL); add_soap_fault(this_ptr, "HTTP", http_msg, NULL, NULL);
从上述代码可以看出,凡是涉及连接不上的情况,返回的FaultCode均为"HTTP"。Soap不像Curl那样有具体的数字错误码来区分不同状态,但利用这个固定的"HTTP"码,即可有效判断出是超时、连接失败等网络层面的问题。
具体的实现代码如下。
ini_set('default_socket_timeout', 30); //定义响应超时为30秒
try {
$options = array(
'cache_wsdl' => 0,
'connection_timeout' => 5, //定义连接超时为5秒
);
libxml_disable_entity_loader(false);
$client = new \SoapClient($url, $options);
return $client->__soapCall($function_name, $arguments);
} catch (\SoapFault $e) {
//超时、连接不上
if($e->faultcode == 'HTTP'){
throw new TimeoutException('连接或请求超时', $e->getCode());
}
}
如果能够成功连接Soap服务,但客户端或服务端出现其他问题,$e->faultcode 通常会返回"WSDL"。可以通过判断此值来区分此类情况。
以上即为在PHP中使用Soap和Curl捕获请求超时及连接超时的方法。希望对各位的学习有所帮助,也欢迎大家继续支持本站。