做了那麼多年的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();

做了那麼多年的PHP開發,真的懂?swoole異步任務實現


分享到:


相關文章: