php swoole thread,做了那么多年的PHP开发,真的懂??swoole异步任务实现

异步任务推送协议

发送短信验证消息

发送邮箱验证消息

编写一个任务基类,声明run方法,子类实现run方法。

添加任务信息的时候,信息里包含任务类名称,和要传递的参数

任务服务器,调用任务实例执行

服务端

#!/usr/bin/env php

class Server

{

private $serv;

public function __construct()

{

$this->serv = new swoole_server("0.0.0.0", 9501);

$this->serv->set(array(

'worker_num' => 1, //一般设置为服务器CPU数的1-4倍

'daemonize' => 1, //以守护进程执行

'max_request' => 10000,

'dispatch_mode' => 2,

'task_worker_num' => 8, //task进程的数量

"task_ipc_mode " => 3, //使用消息队列通信,并设置为争抢模式

"log_file" => "demo.log" ,//所有的输出都会写到日志中

));

$this->serv->on('receive', [$this, 'onReceive']);

$this->serv->on('task', [$this, 'onTask']);

$this->serv->on('finish', [$this, 'onFinish']);

$this->serv->start();

}

public function onReceive(swoole_server $serv, $fd, $from_id, $data)

{

//接收数据,下发任务

$serv->task($data);

$serv->send($fd,'任务ok啦');

}

public function onTask($serv, $task_id, $from_id, $data)

{

//任务处理

$task = json_decode($data,true);

}

public function onFinish($serv, $task_id, $data)

{

//任务结束,回调

echo "finish";

}

}

$server = new Server();

客户端

class Client

{

private $client;

public function __construct()

{

$this->client = new swoole_client(SWOOLE_SOCK_TCP);

if (!$this->client->connect("127.0.0.1", 9501, 1) && !$this->client->isConnected()) {

throw new Exception(sprintf('swoole error: %s', $this->client->errCode));

}

}

public function send($data)

{

$this->client->send(json_encode($data));

return $this->client->recv();

}

public function close()

{

$this->client->close();

}

}

//双方统一传递json数据

$client = new Client();

if ($data = $client->send($data)) {

echo $data;

}

$client->close();

182e4f7f7983

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值