swoole会合并到php吗,thinkphp整合swoole
cli模式下執(zhí)行thinkphp
1、cd 項(xiàng)目根目錄
2、php index.php admin/index/index --執(zhí)行 模塊/控制器/方法名
異步消息隊(duì)列
1、服務(wù)器端核心代碼
/**
* 腳本任務(wù)系統(tǒng)
*/
public function server()
{
$serv = new \swoole_server("0.0.0.0", 8082);
//日志會(huì)記錄你錯(cuò)誤的數(shù)據(jù)
$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);
});
//執(zhí)行任務(wù)模塊
$serv->on('Task', function ($serv, $task_id, $from_id, $data) {
//1秒執(zhí)行一次
$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);
});
//任務(wù)結(jié)束
$serv->on('Finish', function ($serv, $task_id, $data) {
echo "AsyncTask[$task_id] Finish: $data" . PHP_EOL;
});
$serv->start();
}
/* author@zhou
* 功能:發(fā)送數(shù)據(jù)
* return
*/
public function request_post($url ='',$param ='') {
$postUrl = $url;
$curlPost = $param;
$ch = curl_init();//初始化curl
curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定網(wǎng)頁(yè)
curl_setopt($ch, CURLOPT_HEADER, 0);//設(shè)置header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求結(jié)果為字符串且輸出到屏幕上
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);//運(yùn)行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);//手機(jī)號(hào)
}
echo "SUCCESS";
}
}
3、注意事項(xiàng)
定時(shí)任務(wù)執(zhí)行接口請(qǐng)求時(shí)返回 SUCCESS 清除定時(shí)
定時(shí)器會(huì)在單位時(shí)間內(nèi)統(tǒng)一清除
worker_num 默認(rèn)為cpu核數(shù) (1-4倍最合理)
task_worker_num設(shè)置 每秒最大請(qǐng)求數(shù) * 單個(gè)任務(wù)耗時(shí)(單位s) / worker_num
單個(gè)task的處理耗時(shí),如100ms,那一個(gè)進(jìn)程1秒就可以處理1/0.1=10個(gè)task
task投遞的速度,如每秒產(chǎn)生2000個(gè)task
2000/10=200,需要設(shè)置task_worker_num => 200,啟用200個(gè)task進(jìn)程
通用傳參方式:
格式 :function () use ($param1,$param2)
$serv->after(1000*60*2, function () use ($serv,$timer_id) {
$serv->clearTimer($timer_id);
});
總結(jié)
以上是生活随笔為你收集整理的swoole会合并到php吗,thinkphp整合swoole的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 日行灯真的是“鸡肋”吗 上汽大众官方在线
- 下一篇: A+轮融资PPT至今一字未改!蔚来秦力洪