公司中有不少服務(wù)是以curl或者soap方式連接第三方公司做的服務(wù)來交互數(shù)據(jù),最近新增加了個(gè)需求,就是第三方服務(wù)發(fā)版時(shí)候,連接不上對方服務(wù)器時(shí)候要進(jìn)行重試,其它原因?qū)е碌臉I(yè)務(wù)處理失敗,則按失敗處理,不會再進(jìn)行調(diào)用。
思路就是判斷curl或者soap連接不上對方服務(wù)器時(shí)候,拋出TimeoutException異常,捕獲后做重試處理,其它錯(cuò)誤導(dǎo)致的拋出的Exception則按失敗處理。
curl處理
$ch = curl_init($url); $options = array( CURLOPT_RETURNTRANSFER => true, CURLOPT_CONNECTTIMEOUT => 5, //5秒連接時(shí)間 CURLOPT_TIMEOUT => 30, //30秒請求等待時(shí)間 ); curl_setopt_array($ch, $options); $response = curl_exec($ch); if ($no = curl_errno($ch)) { $error = curl_error($ch); curl_close($ch); //$no錯(cuò)誤碼7為連接不上,28為連接上了但請求返回結(jié)果超時(shí) if(in_array(intval($no), [7, 28], true)) { throw new TimeoutException('連接或請求超時(shí)' . $error, $no); } } curl_close($ch);
soap處理
php文檔并沒詳細(xì)寫soap超時(shí)或者連接不上返回的具體代碼,業(yè)務(wù)處理失敗或者連接不上等所有不成功,都會拋出一個(gè)SoapFault異常,看了下php的源碼發(fā)現(xiàn),還是有定義的
php源文件位置 /ext/soap/php_http.c
定義錯(cuò)誤代碼內(nèi)容
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);
從代碼里可以看出來,連接不上都會返回一個(gè)HTTP碼,soap并沒像curl那樣有具體的代碼可以區(qū)分二者,只利用這個(gè)碼可以判斷是超時(shí)或者連接不上等網(wǎng)絡(luò)問題
具體代碼如下
ini_set('default_socket_timeout', 30); //定義響應(yīng)超時(shí)為30秒 try { $options = array( 'cache_wsdl' => 0, 'connection_timeout' => 5, //定義連接超時(shí)為5秒 ); libxml_disable_entity_loader(false); $client = new \SoapClient($url, $options); return $client->__soapCall($function_name, $arguments); } catch (\SoapFault $e) { //超時(shí)、連接不上 if($e->faultcode == 'HTTP'){ throw new TimeoutException('連接或請求超時(shí)', $e->getCode()); } }
可以連接上soap服務(wù),但客戶端或者服務(wù)端出問題 $e->faultcode 會返回WSDL, 用這個(gè)來判斷
以上為php使用soap和curl捕獲請求超時(shí)和連接超時(shí)的方法。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。