首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >并行运行多个POST请求,提高和优化脚本的速度。可能是多线程吗?

并行运行多个POST请求,提高和优化脚本的速度。可能是多线程吗?
EN

Stack Overflow用户
提问于 2017-02-21 11:59:34
回答 1查看 270关注 0票数 1

我希望您能帮助我优化和加快我编写的脚本,以便为多个源检索数据。现在,脚本可能需要2-10分钟才能运行,这取决于一天中的时间。

所有的任何帮助都会得到极大的支持。

解释脚本:

我使用foreach循环来运行五个不同的URL,然后每个URL将执行五个POST请求,并将结果数据写入文件。

我所希望的:

为了提高脚本的速度,我希望五个URL中的每一个都位于不同的函数中,然后并行运行这五个函数。

我读过的选项之一是pcntl_fork,它能用来实现我所需要的东西吗?如果没有,还有其他选择吗?

我的脚本:

代码语言:javascript
复制
foreach($urls as $url){
        $firmato = file_get_html($url, false, stream_context_create($firmato_request));
        if (preg_match('(record totali ([\d]+))', $firmato, $count)) {
            $firmato_count = $count[1];
        };
        $inviato = file_get_html($url, false, stream_context_create($inviato_request));
        if (preg_match('(record totali ([\d]+))', $inviato, $count)) {
            $inviato_count = $count[1];
        };
        $positive = file_get_html($url, false, stream_context_create($positive_request));
        if (preg_match('(record totali ([\d]+))', $positive, $count)) {
            $positive_count = $count[1];
        };
        $negative = file_get_html($url, false, stream_context_create($negative_request));
        if (preg_match('(record totali ([\d]+))', $negative, $count)) {
            $negative_count = $count[1];
        };
        $total = file_get_html($url, false, stream_context_create($default_request));
        if (preg_match('(record totali ([\d]+))', $total, $count)) {
            $default_count = $count[1];
            $other_count = $firmato_count+$inviato_count+$positive_count+$negative_count-$default_count;
        };

        if ($url == 'http://sourceOne.com/MessageServlet') {
            $cacheDir = 'cache/one/';
        } elseif ($url == 'http://sourceTwo.com/MessageServlet') {
            $cacheDir = 'cache/two/';
        } elseif ($url == 'http://sourceThree.com/MessageServlet') {
            $cacheDir = 'cache/three/';
        } elseif ($url == 'http://sourceFour.com/MessageServlet') {
            $cacheDir = 'cache/four/';
        } elseif ($url == 'http://sourceFive.com/MessageServlet') {
            $cacheDir = 'cache/five/';
        }
        $cache_file = $cacheDir.'hour_'.sprintf('%02d', $previousHour).'.txt';
        $data = '<tr><td>'.sprintf('%02d', $previousHour).':00</td><td>'.$firmato_count.'</td><td>'.$inviato_count.'</td><td>'.$positive_count.'</td><td>'.$negative_count.'</td><td>'.$other_count.'</tr>';
        file_put_contents($cache_file, $data);
};
EN

回答 1

Stack Overflow用户

发布于 2017-02-21 12:11:34

您可以使用curl_multi http://php.net/manual/en/function.curl-multi-init.php,也可以使用已经编写好的库(如https://github.com/jmathai/php-multi-curl ),但是这些库无论如何都是用curl_multi编写的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42366722

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档