app/controller/Index.php
<?php
namespace app\controller;
use support\Log;
use support\Request;
use Workerman\Connection\AsyncTcpConnection;
class Index
{
public function index(Request $request)
{
$task = new AsyncTcpConnection('text://127.0.0.1:8889');
for ($i = 1; $i <= 10; $i++) {
$urlBase = 'http://127.0.0.1:8787/index/sleep?id=';
$task->send(json_encode(['cmd' => 'get', 'data' => ['url' => $urlBase . $i]]));
$task->onMessage = function (AsyncTcpConnection $connection, $result) use ($task) {
Log::info('result:' . $result);
};
$task->connect();
}
return response('ok');
}
public function sleep(Request $request)
{
sleep(1);
return response('sleep 1, id:' . $request->input('id'));
}
}
app/process/AsyncTask.php
<?php
namespace process;
use GuzzleHttp\Client;
use Workerman\Connection\TcpConnection;
class AsyncTask
{
public function onConnect(TcpConnection $connection)
{
// var_dump(__METHOD__);
}
public function onMessage(TcpConnection $connection, $data)
{
// var_dump(__METHOD__);
$formatData = json_decode($data, true);
$url = $formatData['data']['url'];
$client = new Client();
$response = $client->get($url);
$content = $response->getBody()->getContents();
$connection->send($content);
}
public function onClose(TcpConnection $connection)
{
// var_dump(__METHOD__);
}
}
config/process.php
return [
'async-task' => [
'handler' => \process\AsyncTask::class,
'listen' => 'text://0.0.0.0:8889',
'count' => 20,
'reusePort' => true,
],
];
启动服务 php start.php start -d
查看状态: php start.php status
runtime/logs/webman-2022-02-26.log
输出内容如下:[2022-02-26 19:18:20] default.INFO: result:sleep 1, id:1 [] []
[2022-02-26 19:18:21] default.INFO: result:sleep 1, id:2 [] []
[2022-02-26 19:18:22] default.INFO: result:sleep 1, id:3 [] []
[2022-02-26 19:18:23] default.INFO: result:sleep 1, id:4 [] []
[2022-02-26 19:18:24] default.INFO: result:sleep 1, id:5 [] []
[2022-02-26 19:18:25] default.INFO: result:sleep 1, id:6 [] []
[2022-02-26 19:18:26] default.INFO: result:sleep 1, id:7 [] []
[2022-02-26 19:18:27] default.INFO: result:sleep 1, id:8 [] []
[2022-02-26 19:18:28] default.INFO: result:sleep 1, id:9 [] []
[2022-02-26 19:18:29] default.INFO: result:sleep 1, id:10 [] []
$ php -v
PHP 7.4.27 (cli) (built: Dec 16 2021 18:14:46) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
with Zend OPcache v7.4.27, Copyright (c), by Zend Technologies
为什么所有的异步任务,都放到一个async-task进程里执行了啊,怎么能平均或随机分配到20个进程里
mac系统不支持
'reusePort' => true,
选项。普通linux系统支持'reusePort' => true,
,并且可以给所有进程平均分配连接。收到,谢谢老大,我试试
可以了,谢谢!
workman中可以使用AsyncTask吗?
可以 https://www.workerman.net/doc/workerman/faq/async-task.html