发布网友 发布时间:2022-04-21 18:35
共1个回答
热心网友 时间:2022-04-07 07:33
php扩展swoole实现实时异步任务队列的方案。安装swoole
pecl 安装:
pecl install swoole
看命令行提示,如果它提示说没有写php.ini,则自己手动在PHP.ini后面加上:
extension = "swoole.so"
服务端
在打算放置脚本的目录(你也可以自行新建)新建Server.php,代码如下:
“`
<?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" => "log/taskqueueu.log" ,//日志
));
$this->serv->on('Receive', array($this, 'onReceive'));
// bind callback
$this->serv->on('Task', array($this, 'onTask'));
$this->serv->on('Finish', array($this, 'onFinish'));
$this->serv->start();
}
public function onReceive( swoole_server $serv, $fd, $from_id, $data ) {
//echo "Get Message From Client {$fd}:{$data}n";
// send a task to task worker.
$serv->task( $data );
}
public function onTask($serv,$task_id,$from_id, $data) {
$array = json_decode( $data , true );
if ($array['url']) {
return $this->httpGet( $array['url'] , $array['param'] );
}