您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

如何解决php中curl和soap方式请求服务超时的问题

2024/3/10 19:03:31发布30次查看
本篇文章主要介绍了php中curl和soap方式请求服务超时问题的解决,内容挺不错的,现在分享给大家,也给大家做个参考。
公司中有不少服务是以curl或者soap方式连接第三方公司做的服务来交互数据,最近新增加了个需求,就是第三方服务发版时候,连接不上对方服务器时候要进行重试,其它原因导致的业务处理失败,则按失败处理,不会再进行调用。
思路就是判断curl或者soap连接不上对方服务器时候,抛出timeoutexception异常,捕获后做重试处理,其它错误导致的抛出的exception则按失败处理。
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处理
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);
从代码里可以看出来,连接不上都会返回一个http码,soap并没像curl那样有具体的代码可以区分二者,只利用这个码可以判断是超时或者连接不上等网络问题
具体代码如下
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数组存入到数据库中
三种php递归函数的实现方法及实现数字的累加
以上就是如何解决php中curl和soap方式请求服务超时的问题的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product