正常情况下,PHP都是同步请求,脚本右上而下依次执行,必须等上一步请求好了,才能进行下一步操作,这种效率在某些时候是不必要的,如发送邮件等操作,是可以异步处理的。
PHP异步也很不少插件,我们使用的是原生的PHP函数,fsockopen(),改函数http请求和socket都可以。
这个函数官网手册已经给出了示例,我贴出我优化后的代码,使用的是http。
public function dealdata(Request $request) ???{ ???????$url = ‘http://test.com/demo/index/temp‘; ???????$param = [ ???????????‘param1‘=>‘name‘, ???????????‘param2‘=>‘value‘ ???????]; ???????$this->syncRequest($url, $param); ???} ???public function syncRequest($url, $param=array(),$timeout =10) ???{ ???????$urlParmas = parse_url($url); ???????$host = $urlParmas[‘host‘]; ???????$path = $urlParmas[‘path‘]; ???????$port = isset($urlParmas[‘port‘])? $urlParmas[‘port‘] :80; ???????$errno = 0; ???????$errstr = ‘‘; ???????$fp = fsockopen($host, $port, $errno, $errstr, $timeout);// ???????stream_set_blocking($fp,0); ???????$query = isset($param)? http_build_query($param) : ‘‘; ???????$out = "POST ".$path." HTTP/1.1\r\n"; ???????$out .= "host:".$host."\r\n"; ???????$out .= "content-length:".strlen($query)."\r\n"; ???????$out .= "content-type:application/x-www-form-urlencoded\r\n"; ???????$out .= "connection:close\r\n\r\n"; ???????$out .= $query; ???????fputs($fp, $out); ???????fclose($fp); ???}
PHP异步请求
原文地址:https://www.cnblogs.com/IT--Loding/p/9063568.html