## 自定义进程执行异步任务 ### 自定义进程 #### 1、`AsyncTcpTask.php` ```php <?php /** * @desc AsyncTcpTask * @author Tinywan(ShaoBo Wan) * @email 756684177@qq.com * @date 2022/2/26 23:35 */ declare(strict_types=1); namespace process\async; use GuzzleHttp\Client; use GuzzleHttp\Exception\GuzzleException; use Workerman\Connection\TcpConnection; class AsyncTcpTask { /** * @param TcpConnection $connection * @param $data * @throws GuzzleException * @throws \Exception */ public function onMessage(TcpConnection $connection, $data) { try { $formatData = json_decode($data, true,512,JSON_THROW_ON_ERROR); $url = $formatData['data']['url']; $client = new Client(); $response = $client->get($url); $content = $response->getBody()->getContents(); $connection->send($content); } catch (\JsonException $e) { throw new \Exception('Data decoding error'); } } } ``` #### (2)`config/process.php` 配置进程 ```php // 异步任务执行 'async.tcp.task' => [ 'handler' => \process\async\AsyncTcpTask::class, 'listen' => 'text://0.0.0.0:8789', 'count' => 10 ], ``` ### 模拟请求服务端 ```php /** * @param Request $request * @return Response */ public function asyncTcpSleep(Request $request): Response { sleep(3); return response('sleep 1, id:' . $request->get('id')); } ``` > 访问地址:http://127.0.0.1:8787/test/async-tcp-sleep?id=2002 ### 用自定义协议 ```php $urlBase = 'http://127.0.0.1:8787/test/async-tcp-sleep?id='; // 异步建立一个自定义协议服务器的连接 $textConnection = new AsyncTcpConnection('text://127.0.0.1:8789'); // 当客户端与Workerman建立连接时(TCP三次握手完成后)触发的回调函数。每个连接只会触发一次onConnect回调。 $textConnection->onConnect = function (AsyncTcpConnection $connection) use ($urlBase){ for ($i = 1; $i <= 20; $i++) { $connection->send(json_encode([ 'cmd' => 'get', 'data' => [ 'url' => $urlBase . $i ] ])); } }; // 当客户端通过连接发来数据时(Workerman收到数据时)触发的回调函数,即:请求响应的数据包 $textConnection->onMessage = function (AsyncTcpConnection $connection, $result) { Log::info('result2022 = ' . $result.', connection_id = '.$connection->id); }; // 当客户端连接与Workerman断开时触发的回调函数。 $textConnection->onClose = function(AsyncTcpConnection $connection) { // 如果连接断开,则在3秒后重连 $connection->reConnect(3); }; // 执行异步连接操作。此方法会立刻返回。 $textConnection->connect(); ```