php 请求第三方接口超时的解决办法

我们在开发过程中,可能会遇到请求第三方的接口,比如获取IP地址的详细信息,一旦第三方接口挂掉,会影响到我们整个程序。我们该如何解决?

方法一:使用stream_context_create资源流,再使用file_get_contents请求

$timeout=array(
    'http'=>array(
        'timeout'=>5
    )
);
$ctx=stream_context_create($timeout);
$text=file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=49.70.205.170',0,$ctx);
echo $text;

方法二:使用try_catch和default_socket_timeout配合使用

try{
   ini_set('default_socket_timeout',3);//三秒超时
//调用外部接口,如file,file_get_content,webservice

}catch(Exception $e){
   print_r($e);

版权声明:本文为weixin_42362496原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。