Skip to content

Commit

Permalink
up
Browse files Browse the repository at this point in the history
  • Loading branch information
yf committed Dec 25, 2018
1 parent 901eddb commit 206f052
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 13 deletions.
39 changes: 26 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
@@ -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()}");
}
```
48 changes: 48 additions & 0 deletions src/Multi.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php
/**
* Created by PhpStorm.
* User: yf
* Date: 2018/12/25
* Time: 2:12 PM
*/

namespace EasySwoole\HttpClient;


use Swoole\Coroutine\Channel;

class Multi
{
protected $list = [];

function addTask($name,HttpClient $client):Multi
{
$this->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;
}
}

0 comments on commit 206f052

Please sign in to comment.