Swoole实时任务异步调用实例

服务端

新建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";  
        $serv->task($data);  
    }  
  
    public function onTask($serv, $task_id, $from_id, $data)  
    {  
          //在这里进行脚本执行处理操作
          echo $data;

    }  
  
    public function onFinish($serv, $task_id, $data)  
    {  
        //任务完成自动调用
    }  
  
  
}  
  
$server = new Server();  
  
}  
  
$server = new Server();  

客户端:

新建Client.php

<?php  
  
class Client  
{  
    private $client;  
  
    public function __construct()  
    {  
        $this->client = new swoole_client(SWOOLE_SOCK_TCP);  
    }  
  
    public function connect()  
    {  
        if (!$this->client->connect("127.0.0.1", 9501, 1)) {  
            throw new Exception(sprintf('Swoole Error: %s', $this->client->errCode));  
        }  
    }  
  //传输数据
    public function send($data)  
    {  
        if ($this->client->isConnected()) {  
          
            return $this->client->send($data);  
        } else {  
            throw new Exception('Swoole Server does not connected.');  
        }  
    }  
  
    public function close()  
    {  
        $this->client->close();  
    }  
}  
  
$data = array(  
    "params"=>"参数信息"
);  
$client = new Client();  
$client->connect();  
if ($client->send($data)) {  
    echo 'success';  
} else {  
    echo 'fail';  
}  
$client->close();
保存好代码,在命令行或者浏览器中执行Client.php,便实现了异步任务队列。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值