diff --git a/README.md b/README.md index 829fd95..556b11f 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,32 @@ # 协程HttpClient - +## 单次请求 ``` - $url = 'http://docker.local.com/test.php/?get1=get1'; - $test = new \EasySwoole\HttpClient\HttpClient($url); - //$test->post(); +$url = 'http://docker.local.com/test.php/?get1=get1'; +$test = new \EasySwoole\HttpClient\HttpClient($url); +//$test->post(); + +$test->addCookie('c1','c1')->addCookie('c2','c2'); +$test->post([ + 'post1'=>'post1' +]); +$test->setHeader('myHeader','myHeader'); +$test->addData('sasasas','test.file','text','test.file'); - $test->addCookie('c1','c1')->addCookie('c2','c2'); - $test->post([ - 'post1'=>'post1' - ]); - $test->setHeader('myHeader','myHeader'); - $test->addData('sasasas','test.file','text','test.file'); +//$test->postJSON(json_encode(['json'=>1])); - //$test->postJSON(json_encode(['json'=>1])); +$ret = $test->exec(); +var_dump($ret->getBody()); +``` - $ret = $test->exec(); - var_dump($ret->getBody()); +## 并发请求 +``` +$url = 'http://docker.local.com/test.php/?get1=get1'; +$test = new \EasySwoole\HttpClient\HttpClient($url); +$multi = new \EasySwoole\HttpClient\Multi(); +$multi->addTask('t1',$test); +$multi->addTask('t2',$test); +$ret = $multi->exec(); +foreach ($ret as $taskName => $response){ + var_dump("task {$taskName} finish and body is {$response->getBody()}"); +} ``` \ No newline at end of file diff --git a/src/Multi.php b/src/Multi.php new file mode 100644 index 0000000..fac929d --- /dev/null +++ b/src/Multi.php @@ -0,0 +1,48 @@ +list[$name] = $client; + return $this; + } + + function exec(float $timeout = 1.0):array + { + $channel = new Channel(count($this->list)+1); + foreach ($this->list as $name => $client) + { + go(function ()use($channel,$name,$client){ + $channel->push([ + $name=>$client->exec() + ]); + }); + } + $ret = []; + $start = microtime(true); + while (1){ + if(round(microtime(true) - $start,3) > $timeout ){ + break; + } + $temp = $channel->pop(0.01); + if(is_array($temp)){ + $ret = $ret+$temp; + } + } + return $ret; + } +} \ No newline at end of file