Webman框架使用异步任务

首先在app目录下创建Task.php

<?php
namespace app;

use Workerman\Connection\TcpConnection;
class Task
{
/**
* 只会执行一次
* @return void
*/
public function onWorkerStart(){
  echo "进程启动";
}

public function onMessage($connection, $task_data)
{
  $connection->send(json_encode(['name' => 1]));
}

public function onConnect ($connection){
  echo "new connection from ip " . $connection->getRemoteIp() . "\n";
}

}

配置 config/process.php,新增

return [
 ......
'task' => [
   'handler' => app\Task::class,
  'listen' => 'text://0.0.0.0:12345',
  'count' => 20, //进程数量,默认为1
  'reusePort' => true, //是否负载均衡到n个进程
],
];

调用


<?php

namespace app\controller;

use app;
use app\Message;
use Workerman\Connection\AsyncTcpConnection;

class IndexController
{
/**
* 用来测试远程服务器是否还正常启动
* @return \support\Response
*/
public function index()
{
  $taskConnection = new AsyncTcpConnection('text://127.0.0.1:12345');
  // 发送数据
  $taskConnection->send(json_encode(['cmd' => 'get', 'data' => []]));
  $taskConnection->onMessage = function (AsyncTcpConnection $taskConnection, $task_result) {
  sleep(3); //这里模拟延迟
  // 结果
  var_dump($task_result);
  // 获得结果后记得关闭异步连接
  $taskConnection->close();
  };
  $taskConnection->connect();
  return json(['code' => Message::Success]);
}
}

由于是异步,所以不用等待sleep,直接输出

posted @ 2023-11-20 13:59  朝阳1  阅读(307)  评论(0编辑  收藏  举报