這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)如何在PHP中使用Swoole實(shí)現(xiàn)一個(gè)實(shí)時(shí)異步任務(wù)隊(duì)列,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
創(chuàng)新互聯(lián)專注于和平企業(yè)網(wǎng)站建設(shè),響應(yīng)式網(wǎng)站設(shè)計(jì),成都做商城網(wǎng)站。和平網(wǎng)站建設(shè)公司,為和平等地區(qū)提供建站服務(wù)。全流程按需定制網(wǎng)站,專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)服務(wù)端
在打算放置腳本的目錄(你也可以自行新建)新建Server.php,代碼如下
serv = new swoole_server("0.0.0.0", 9501); $this->serv->set(array( 'worker_num' => 1, //一般設(shè)置為服務(wù)器CPU數(shù)的1-4倍 'daemonize' => 1, //以守護(hù)進(jìn)程執(zhí)行 'max_request' => 10000, 'dispatch_mode' => 2, 'task_worker_num' => 8, //task進(jìn)程的數(shù)量 "task_ipc_mode " => 3, //使用消息隊(duì)列通信,并設(shè)置為爭(zhēng)搶模式 //"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); //設(shè)置網(wǎng)址 curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1); //將curl_exec的結(jié)果返回 curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curlObj, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($curlObj, CURLOPT_HEADER, 0); //是否輸出返回頭信息 $response = curl_exec($curlObj); //執(zhí)行 curl_close($curlObj); //關(guān)閉會(huì)話 return $response; } } $server = new Server();
客戶端
啟動(dòng)服務(wù)后,讓我們看看如何調(diào)用服務(wù)。新建測(cè)試文件Client_test.php
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實(shí)現(xiàn)一個(gè)實(shí)時(shí)異步任務(wù)隊(duì)列了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。