12
12
use App \Http \Repository \MultithreadingRepository ;
13
13
use App \Models \ApiExcel ;
14
14
use Hhxsv5 \LaravelS \Swoole \WebSocketHandlerInterface ;
15
+ use Illuminate \Support \Facades \Redis ;
15
16
use Swoole \Http \Request ;
16
17
use Swoole \WebSocket \Frame ;
17
18
use Swoole \WebSocket \Server ;
@@ -23,6 +24,8 @@ class WebSocketService implements WebSocketHandlerInterface
23
24
{
24
25
public $ perPage = 10 ;
25
26
27
+ private $ redis ;
28
+
26
29
// 声明没有参数的构造函数
27
30
public function __construct ()
28
31
{
@@ -52,26 +55,34 @@ public function onOpen($server, $request)
52
55
if (!$ state ) {
53
56
break ;
54
57
}
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
+ }
55
82
}
56
83
}
57
84
return '' ;
58
85
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
-
75
86
// throw new \Exception('an exception');// 此时抛出的异常上层会忽略,并记录到Swoole日志,需要开发者try/catch捕获处理
76
87
}
77
88
@@ -147,4 +158,12 @@ private function apiExcel()
147
158
148
159
return $ this ->outJson (200 , $ items );
149
160
}
161
+
162
+ private function incrKey ($ key )
163
+ {
164
+ if (!isset ($ this ->$ key )) {
165
+ $ this ->$ key = 1 ;
166
+ }
167
+ $ this ->$ key ++;
168
+ }
150
169
}
0 commit comments