swoole服务端与客户端 异步任务
服务端:Server.php 在Linux服务器上直接执行:php 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 => 4, //一般设置为服务器CPU数的1-4倍 daemonize => 1, //以守护进程执行 max_request => 10000, dispatch_mode => 2, task_worker_num => 4, //task进程的数量 "task_ipc_mode " => 3, //使用消息队列通信,并设置为争抢模式 //"log_file" => "log/taskqueueu.log" ,//日志 )); $this->serv->on(Receive, array($this, onReceive)); $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) { $serv->task($data); } public function onTask($serv, $task_id, $from_id, $data) { $array = json_decode($data, true); $token = ; if(isset($array[token])){ $token = $array[token]; } $this->curl_request($array[url], $array[data],$token); } public function onFinish($serv, $task_id, $data) { } //curl调用接口 protected function curl_request($url,array $data = [],$token = ) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); if($token){ curl_setopt($curl, CURLOPT_HTTPHEADER, [token: .$token]); } if (!empty($data)){ curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($curl); curl_close($curl); return $output; } } $server = new Server();
客户端:Client.php
<?php namespace appadminlogic; class Client { private $client; //端口号 private $port = 9501; public function __construct() { $this->client = new swoole_client(SWOOLE_SOCK_TCP); } public function connect() { if (!$this->client->connect("127.0.0.1", $this->port, 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(); } }
调用方式:
$arr[url] = ConstGroup::DESIGNER_URL . /v1/orderTemExport;//异步控制器 $arr[data] = $params;//客户端传给控制器的参数 $client = new appadminlogicClient(); $client->connect(); if ($client->send($arr)) { $client->close(); ApiResponse::success(导入成功); }
上一篇:
IDEA上Java项目控制台中文乱码