我正在寻找一个解决方案,以切换IP时自动运行PHP爬虫。我有一个自定义的爬虫,它运行100个线程,但由于油门限制,我经常被阻塞。因为PHP不支持多线程,所以我设置了windows调度程序来并行运行PHP应用程序。
我想为每个线程分配一个不同的IP地址,并欢迎任何建议来克服这个问题。
发布于 2014-04-16 20:45:19
在PHP中可以实现多线程
有些人甚至会说这是微不足道的。
<?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或其他魔术将客户端配置为使用为线程设置的接口。
进一步阅读:
https://stackoverflow.com/questions/23059404
复制相似问题