【问题标题】:Fastest or most robust way to make 7 soap api requests in parallel并行发出 7 个soap api 请求的最快或最稳健的方法
【发布时间】:2014-03-03 20:13:11
【问题描述】:

我的网络应用程序需要发出 7 个不同的 soap wsdl api 请求来完成一项任务(我需要用户等待所有请求的结果)。每个请求的平均响应时间为 500 毫秒到 1.7 秒。我需要并行运行所有这些请求以加快进程。 最好的方法是什么:

  1. pthreads 或
  2. 齿轮工人
  3. 分叉进程
  4. curl multi(我必须构建 xml 肥皂体)

【问题讨论】:

  • 这些都不是最佳的。碰巧,您是否需要等待它们完成后再将响应发送回标准输出? (即,这可以异步完成吗?)
  • 是的。我需要在完成任务之前回复所有回复
  • +1 不知道为什么这个问题被否决了;知道请求/响应是否可以与 SoapClient 分开是很有趣的。
  • 您还希望 SoapClient 处理响应吗?

标签: php multithreading curl soap


【解决方案1】:

首先要说的是,创建线程以直接响应 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 的缓存...

【讨论】:

    猜你喜欢
    • 2017-10-04
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多