thinkphp整合swoole
cli模式下执行thinkphp
1、cd 项目根目录
2、php index.php admin/index/index --执行 模块/控制器/方法名
异步消息队列
1、服务器端核心代码
/** * 脚本任务系统 */ public function server() { $serv = new \swoole_server("0.0.0.0", 8082); //日志会记录你错误的数据 $serv->set(array('task_worker_num' => 20, 'log_file' => './swoole.log')); $serv->on('Receive', function ($serv, $fd, $from_id, $data) { $task_id = $serv->task($data); }); //执行任务模块 $serv->on('Task', function ($serv, $task_id, $from_id, $data) { //1秒执行一次 $num = 0; $timer_id = $serv->tick(1000, function ($id) use ($serv,$data,$num) { $url = "http://notify.yingxiaom.top/index.php/admin/index/test"; $result = $this->request_post($url); if($result == 'SUCCESS'){ echo "1"; file_put_contents("b.txt","1",FILE_APPEND); $serv->clearTimer($id); } }); //10秒后销毁 $serv->after(1000*60*2, function () use ($serv,$timer_id) { $serv->clearTimer($timer_id); }); $serv->finish($data); }); //任务结束 $serv->on('Finish', function ($serv, $task_id, $data) { echo "AsyncTask[$task_id] Finish: $data" . PHP_EOL; }); $serv->start(); } /* author@zhou * 功能:发送数据 * return */ public function request_post($url ='',$param ='') { $postUrl = $url; $curlPost = $param; $ch = curl_init();//初始化curl curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页 curl_setopt($ch, CURLOPT_HEADER, 0);//设置header curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上 curl_setopt($ch, CURLOPT_POST, 1);//post提交方式 curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8','Content-Length: ' . strlen($curlPost))); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false); $data = curl_exec($ch);//运行curl // var_dump(curl_errno($ch));die; curl_close($ch); return $data; }
2、客户端代码
/** * description:客户端 */ public function client() { $phone = I("phone"); $client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC); $ret = $client->connect("127.0.0.1", 8082); if(empty($ret)){ echo 'error!connect to swoole_server failed'; } else { if($phone){ $client->send($phone);//手机号 } echo "SUCCESS"; } }
3、注意事项
定时任务执行接口请求时返回 SUCCESS 清除定时
定时器会在单位时间内统一清除
worker_num 默认为cpu核数 (1-4倍最合理)
task_worker_num设置 每秒最大请求数 * 单个任务耗时(单位s) / worker_num
单个task的处理耗时,如100ms,那一个进程1秒就可以处理1/0.1=10个task
task投递的速度,如每秒产生2000个task
2000/10=200,需要设置task_worker_num => 200,启用200个task进程
通用传参方式:
格式 :function () use ($param1,$param2)
$serv->after(1000*60*2, function () use ($serv,$timer_id) {
$serv->clearTimer($timer_id);
});