1212use App \Http \Repository \MultithreadingRepository ;
1313use App \Models \ApiExcel ;
1414use Hhxsv5 \LaravelS \Swoole \WebSocketHandlerInterface ;
15+ use Illuminate \Support \Facades \Redis ;
1516use Swoole \Http \Request ;
1617use Swoole \WebSocket \Frame ;
1718use Swoole \WebSocket \Server ;
@@ -23,6 +24,8 @@ class WebSocketService implements WebSocketHandlerInterface
2324{
2425 public $ perPage = 10 ;
2526
27+ private $ redis ;
28+
2629 // 声明没有参数的构造函数
2730 public function __construct ()
2831 {
@@ -52,26 +55,34 @@ public function onOpen($server, $request)
5255 if (!$ state ) {
5356 break ;
5457 }
58+ // 每个用户 fd 限制请求次数
59+ $ redisKey = 'websocket_fd_ ' .$ request ->fd ;
60+ if (empty ($ this ->redis )) {
61+ $ this ->redis = Redis::connection ();
62+ }
63+ // 如果获取不到 redis 实例,使用总计数次数
64+ if ($ this ->redis ) {
65+ $ count = $ this ->redis ->incr ($ redisKey );
66+ if ($ count == 1 ) {
67+ // 设置过期时间
68+ $ this ->redis ->expire ($ redisKey , 600 );
69+ }
70+ if ($ count > 200 ) { // 防止刷单的安全拦截
71+ break ; // 超出就跳出循环
72+ }
73+ } else {
74+ $ count_fd = 'count_ ' .$ request ->fd ;
75+ $ this ->incrKey ($ count_fd );
76+ // 单fd超过 1000 次跳出循环
77+ if ($ this ->$ count_fd > 1000 ) {
78+ unset($ this ->$ count_fd );
79+ break ;
80+ }
81+ }
5582 }
5683 }
5784 return '' ;
5885
59- // if (isset($req['id']) && $req['id'] == floor($req['id'])) {
60- // while (true) {
61- // // 3. 输出完成率
62- // $rate = MultithreadingRepository::getInstent()->completionRate($req['id']);
63- // $data = $this->outJson(200, ['rate' => $rate]);
64- // $server->push($request->fd, $data);
65- // sleep(3);
66- //
67- // if ($rate >= 100) {
68- // break;
69- // }
70- // }
71- // } else {
72- // $server->push($request->fd, $this->outJson(200, ['rate' => '100']));
73- // }
74-
7586 // throw new \Exception('an exception');// 此时抛出的异常上层会忽略,并记录到Swoole日志,需要开发者try/catch捕获处理
7687 }
7788
@@ -147,4 +158,12 @@ private function apiExcel()
147158
148159 return $ this ->outJson (200 , $ items );
149160 }
161+
162+ private function incrKey ($ key )
163+ {
164+ if (!isset ($ this ->$ key )) {
165+ $ this ->$ key = 1 ;
166+ }
167+ $ this ->$ key ++;
168+ }
150169}
0 commit comments