您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
swoole系列-在携程风格http服务器中实现异步"file_get_content"
发布时间:2022-05-17 21:33:51编辑:雪饮阅读()
这里以批量下载46个法本信息的网页内容为例:
<?php
use Swoole\Coroutine\Http\Server;
use function Swoole\Coroutine\run;
use function Swoole\Coroutine\go;
use Swoole\Coroutine\Channel;
$serv = new Swoole\Http\Server("0.0.0.0", 9503, SWOOLE_BASE);
$serv->on('request', function ($req, $resp) {
$len=46;
$start_time=time();
$chan = new Channel($len);
$host='www.farben.com.cn';
for($i=1;$i<=$len;$i++){
go(function () use ($chan,$i,$host) {
$cli = new Swoole\Coroutine\Http\Client($host, 443,true);
$cli->set(['timeout' => 10]);
$cli->setHeaders([
'Host' => $host,
"User-Agent" => 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36',
'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding' => 'gzip, deflate, br',
]);
$path="/news/list_lcid_14_page_".$i.".html";
$ret = $cli->get("/news/list_lcid_14_page_".$i.".html");
//这里需要注意,push的结构必须是key=》val的结构,且key要唯一,比如用变量$i这样就可以
$chan->push([$path => $cli->body]);
});
}
$result = [];
for ($i = 0; $i <$len; $i++)
{
$result += $chan->pop();
}
$data["result"]=$result;
$data["use_time"]=time()-$start_time;
$resp->end(json_encode($data));
});
$serv->start();
然后在命令行运行如php cs.php
然后在浏览器访问如:192.168.31.80:9503即可
关键字词:file_get_content,异步,swoole,http
相关文章
- 基于GuzzleHttp(thinkphp5实现原生获取獲取微信公衆平
- workerman-websocket协议-websocket协议握手(get,serv
- http反向代理環境下获取真实ip(基於workerman)
- https在反向代理環境下获取真实ip(基於workerman實現)
- workerman作爲客戶端系列之http代理搭建
- workerman創建https服務(普通請求轉https請求,基於寶塔
- workerman創建https服務
- workerman异步消息队列组件-rabbitmq
- workerman異步http組件-http-client
- workerman异步消息队列组件-redis-queue