这期内容当中小编将会给大家带来有关如何在PHP中使用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"; // 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']); } } public function onFinish($serv, $task_id, $data) { //echo "Task {$task_id} finish\n"; //echo "Result: {$data}\n"; } protected function httpGet($url, $data) { if ($data) { $url .= '?' . http_build_query($data); } $curlObj = curl_init(); //初始化curl, curl_setopt($curlObj, CURLOPT_URL, $url); //设置网址 curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1); //将curl_exec的结果返回 curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curlObj, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($curlObj, CURLOPT_HEADER, 0); //是否输出返回头信息 $response = curl_exec($curlObj); //执行 curl_close($curlObj); //关闭会话 return $response; } } $server = new Server();
客户端
启动服务后,让我们看看如何调用服务。新建测试文件Client_test.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()) { if (!is_string($data)) { $data = json_encode($data); } return $this->client->send($data); } else { throw new Exception('Swoole Server does not connected.'); } } public function close() { $this->client->close(); } } $data = array( "url" => "http://192.168.10.19/send_mail", "param" => array( "username" => 'test', "password" => 'test' ) ); $client = new Client(); $client->connect(); if ($client->send($data)) { echo 'success'; } else { echo 'fail'; } $client->close();
上述就是小编为大家分享的如何在PHP中使用Swoole实现一个实时异步任务队列了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。