我的网络应用需要制作7个不同的soap wsdl api请求来完成一项任务(我需要用户等待所有请求的结果)。每个请求的平均响应时间为500毫秒到1.7秒。我需要并行运行所有这些请求以加快进程。 最好的方法是什么:
答案 0 :(得分:2)
首先要说的是,在直接响应Web请求时创建线程绝不是一个好主意,想一想实际扩展到多远。
如果为每个出现的人创建7个线程并且有100个人出现,那么你会要求你的硬件同时执行700个线程,这真的要求很多......
但是,可伸缩性不是我可以帮助你的东西,所以我只是回答这个问题。
<?php
/* the first service I could find that worked without authorization */
define("WSDL", "http://www.webservicex.net/uklocation.asmx?WSDL");
class CountyData {
/* this works around simplexmlelements being unsafe (and shit) */
public function __construct(SimpleXMLElement $element) {
$this->town = (string)$element->Town;
$this->code = (string)$element->PostCode;
}
public function run(){}
protected $town;
protected $code;
}
class GetCountyData extends Thread {
public function __construct($county) {
$this->county = $county;
}
public function run() {
$soap = new SoapClient(WSDL);
$result = $soap->getUkLocationByCounty(array(
"County" => $this->county
));
foreach (simplexml_load_string(
$result->GetUKLocationByCountyResult) as $element) {
$this[] = new CountyData($element);
}
}
protected $county;
}
$threads = [];
$thread = 0;
$threaded = true; # change to false to test without threading
$counties = [ # will create as many threads as there are counties
"Buckinghamshire",
"Berkshire",
"Yorkshire",
"London",
"Kent",
"Sussex",
"Essex"
];
while ($thread < count($counties)) {
$threads[$thread] =
new GetCountyData($counties[$thread]);
if ($threaded) {
$threads[$thread]->start();
} else $threads[$thread]->run();
$thread++;
}
if ($threaded)
foreach ($threads as $thread)
$thread->join();
foreach ($threads as $county => $data) {
printf(
"Data for %s %d\n", $counties[$county], count($data));
}
?>
请注意,SoapClient实例不是,也不能共享,这可能会让你失望,你可能想要启用wsdl的缓存......