ThinkPHP异步调用
2023-03-29 23:03:03
96
{{single.collect_count}}

1.问题描述:在一个php文件中,A函数调用B函数,B函数需要5分钟才能结束,页面处于一直加载的状态,且不能关闭,A函数其他语句均不能运行。

function A(){$this->B();echo "B不结束,不能运行";}function B(){sleep(500);}

2.解决办法 运用fsockopen函数

function A(){$this->_sock($_SERVER['HTTP_HOST'].'/index.php/user/test/B?sampleid='.$sampleid);echo "B不结束,也能运行";}function B(){sleep(500);} //异步调用function _sock($url) {$host = parse_url($url,PHP_URL_HOST);$port = parse_url($url,PHP_URL_PORT);$port = $port ? $port : 80;$scheme = parse_url($url,PHP_URL_SCHEME);$path = parse_url($url,PHP_URL_PATH);$query = parse_url($url,PHP_URL_QUERY);if($query) $path .= '?'.$query;if($scheme == 'https') {$host = 'ssl://'.$host;}$fp = fsockopen($host,$port,$error_code,$error_msg,1);if(!$fp) {return array('error_code' => $error_code,'error_msg' => $error_msg);}else {stream_set_blocking($fp,true);//开启了手册上说的非阻塞模式stream_set_timeout($fp,1);//设置超时$header = "GET $path HTTP/1.1\r\n";$header.="Host: $host\r\n";$header.="Connection: close\r\n\r\n";//长连接关闭fwrite($fp, $header);usleep(1000); // 这一句也是关键,如果没有这延时,可能在nginx服务器上就无法执行成功fclose($fp);return array('error_code' => 0);}}

参考资料:https://blog.csdn.net/qq_22823581/article/details/77712987

 

回帖
全部回帖({{commentCount}})
{{item.user.nickname}} {{item.user.group_title}} {{item.friend_time}}
{{item.content}}
{{item.comment_content_show ? '取消' : '回复'}} 删除
回帖
{{reply.user.nickname}} {{reply.user.group_title}} {{reply.friend_time}}
{{reply.content}}
{{reply.comment_content_show ? '取消' : '回复'}} 删除
回帖
收起
没有更多啦~
{{commentLoading ? '加载中...' : '查看更多评论'}}