swoole协程curl请求方法

function swoole_http_get($urls){
    $result = [];
    \Yurun\Util\YurunHttp::setDefaultHandler(\Yurun\Util\YurunHttp\Handler\Swoole::class);
    $scheduler = new \Swoole\Coroutine\Scheduler();
    foreach ($urls as $url) {
        $scheduler->add(function () use ($url,&$result) {
            $http = new \Yurun\Util\HttpRequest();
            $http->Headers([
                'Content-Type'=>'application/json; charset=UTF-8',
                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
            ]);
            $response = $http->get($url, [], ['timeout' => 5]);
            $resp =  $response->json(true);$result[] =  $resp;
        });
    }
    $scheduler->start();
    return $result;
}

 

  • 此方法需要安装YurunHttp扩展包,composer require yurunsoft/yurun-http。 文档地址:https://doc.yurunsoft.com/YurunHttp/165
  • 此方法目前是get请求,需要post,自行参考文档封装即可。
  • 使用需要安装swoole扩展,并且深入了解swoole运行模式和php-fpm的差异。
posted @ 2024-12-07 10:40  知风阁  阅读(60)  评论(0)    收藏  举报