Question

my web app requires making 7 different soap wsdl api requests to complete one task (I need the users to wait for the result of all the requests). The avg response time is 500 ms to 1.7 second for each request. I need to run all these request in parallel to speed up the process. What's the best way to do that:

  1. pthreads or
  2. Gearman workers
  3. fork process
  4. curl multi (i have to build the xml soap body)

No correct solution

OTHER TIPS

Well the first thing to say is, it's never really a good idea to create threads in direct response to a web request, think about how far that will actually scale.

If you create 7 threads for everyone that comes along and 100 people turn up, you'll be asking your hardware to execute 700 threads concurrently, which is quite a lot to ask of anything really...

However, scalability is not something I can usefully help you with, so I'll just answer the question.

<?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));
}
?>

Note that, the SoapClient instance is not, and can not be shared, this may well slow you down, you might want to enable caching of wsdl's ...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top