目前工作中遇到这种要求:移动端实时上传自己的坐标位置,再广播给群组中的其他人。(目前不考虑其他协议)要扛得住1W的并发。
思路:每个人在请求其他人位置的时候,把自己的位置也传上去,服务器写到内存表里面,返回所有人位置。
代码如下:
<?php
//用内存表进行数据的共享 读写效率超高
$table = new swoole_table(1024);//$size参数指定表格的最大行数,必须为2的指数,如1024,8192,65536等
$table->column('uid', swoole_table::TYPE_INT, 8); //1,2,4,8
$table->column('location', swoole_table::TYPE_STRING, 64);
$table->create();
//创建http_server 将内存表作为一个内部成员变量来使用
$serv = new swoole_http_server(0.0.0.0,9502);
$serv->set(["worker_num"=>10]);
$serv->on("onrequest",function($request,$response)use($table){
$uid = $request->get['uid'];
$location = $request->get['location'];
$table->set("location_uid".$uid,['uid'=>$uid,'location'=>$location]);
//遍历内存表获取所有数据
foreach($table as $lo){
$infos[] = $lo;
}
$response->end(json_encode($infos));
});
$serv->start();
写完之后,发现用charles做1W并发压测的时候,服务器报错
swServer_master_onAccept: accept() failed. Error: Too many open files[24]
调整ulimit -n 10000
设置 就可以做到1W并发了。