首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >基于PHP crawler的IP切换

基于PHP crawler的IP切换
EN

Stack Overflow用户
提问于 2014-04-14 19:53:09
回答 1查看 312关注 0票数 0

我正在寻找一个解决方案,以切换IP时自动运行PHP爬虫。我有一个自定义的爬虫,它运行100个线程,但由于油门限制,我经常被阻塞。因为PHP不支持多线程,所以我设置了windows调度程序来并行运行PHP应用程序。

我想为每个线程分配一个不同的IP地址,并欢迎任何建议来克服这个问题。

EN

回答 1

Stack Overflow用户

发布于 2014-04-16 20:45:19

在PHP中可以实现多线程

有些人甚至会说这是微不足道的。

代码语言:javascript
运行
复制
<?php
define('LOG', Mutex::create());

/* make output when writing to stdout thread safe (so, readable) */
function slog($message, $args = []) {
    $args = func_get_args();
    if (($message = array_shift($args))) {
        Mutex::lock(LOG);
        echo vsprintf($message, $args);
        Mutex::unlock(LOG);
    }
}

class WebCrawler extends Thread {

    public function __construct($interface) {
        $this->interface = $interface;
    }

    public function run() {
        slog("Thread %lu using %s\n", 
            $this->getThreadId(), $this->getInterface());
    }

    public function getInterface() { 
        return $this->interface; 
    }

    protected $interface;
}

$interfaces = [
    "192.168.0.1",
    "192.168.0.2",
    "192.168.0.3",
    "192.168.0.4",
    "192.168.0.5"
];

$threads = [];
$thread = 0;
while (count($threads) < count($interfaces)) {
    $threads[$thread] = new WebCrawler($interfaces[$thread]);
    $threads[$thread]->start();
    $thread++;
}

foreach ($threads as $thread)
    $thread->join();

Mutex::destroy(LOG);
?>

上面的代码从预定义的接口列表中为每个线程提供一个接口。然后,您可以使用CURLOPT_INTERFACE或其他魔术将客户端配置为使用为线程设置的接口。

进一步阅读:

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

https://stackoverflow.com/questions/23059404

复制
相关文章

相似问题

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