Hyperf 框架中开协程的几种方式
<?php
declare(strict_types=1);
namespace App\Controller;
use Hyperf\Utils\Parallel;
use Hyperf\Utils\WaitGroup;
use Swoole\Coroutine\Channel;
use Hyperf\Guzzle\ClientFactory;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Di\Annotation\Inject;
class CoController
{
private $clientFactory;
public function sleep(RequestInterface $request)
{
$seconds = $request->query('seconds', 1);
sleep((int)$seconds);
var_dump('sleep hello ====> ' . $seconds);
return $seconds;
}
public function test()
{
$channel = new Channel();
co(function () use ($channel) {
$client = $this->clientFactory->create();
$client->get('127.0.0.1:9516/co/sleep?seconds=2');
$channel->push(123);
});
co(function () use ($channel) {
$client = $this->clientFactory->create();
$client->get('127.0.0.1:9516/co/sleep?seconds=2');
$channel->push(321);
});
$result[] = $channel->pop();
$result[] = $channel->pop();
return $result;
}
public function test1()
{
$wg = new WaitGroup();
$wg->add(2);
$result = [];
co(function () use ($wg, &$result) {
$client = $this->clientFactory->create();
$client->get('127.0.0.1:9516/co/sleep?seconds=2');
$result[] = 123;
$wg->done();
});
co(function () use ($wg, &$result) {
$client = $this->clientFactory->create();
$client->get('127.0.0.1:9516/co/sleep?seconds=2');
$result[] = 321;
$wg->done();
});
$wg->wait();
return $result;
}
public function test2()
{
$parallel = new Parallel();
$parallel->add(function () {
$client = $this->clientFactory->create();
$client->get('127.0.0.1:9516/co/sleep?seconds=2');
return 123;
}, 'foo');
$parallel->add(function () {
$client = $this->clientFactory->create();
$client->get('127.0.0.1:9516/co/sleep?seconds=2');
return 321;
}, 'bar');
$result = $parallel->wait();
return $result;
}
public function test3()
{
$result = parallel([
'foo' => function () {
$client = $this->clientFactory->create();
$client->get('127.0.0.1:9516/co/sleep?seconds=2');
return 123;
},
'bar' => function () {
$client = $this->clientFactory->create();
$client->get('127.0.0.1:9516/co/sleep?seconds=2');
return 321;
},
]);
return $result;
}
}