Skip to content

Commit ec17a90

Browse files
committed
只使用一个缓存键完成计数固定窗口
1 parent 14f01fe commit ec17a90

File tree

1 file changed

+2
-10
lines changed

1 file changed

+2
-10
lines changed

src/throttle/CounterFixed.php

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,21 +14,13 @@ class CounterFixed extends ThrottleAbstract
1414
public function allowRequest(string $key, float $micronow, int $max_requests, int $duration, $cache)
1515
{
1616
$cur_requests = $cache->get($key, 0);
17-
$limit_flag = $cache->get($key . 'flag', null);
1817
$now = (int) $micronow;
1918
$wait_reset_seconds = $duration - $now % $duration; // 距离下次重置还有n秒时间
20-
2119
$this->wait_seconds = $wait_reset_seconds % $duration + 1;
22-
if ($limit_flag === null) { // 首次访问
23-
$cur_requests = 1;
24-
$cache->set($key, $cur_requests, $wait_reset_seconds);
25-
$cache->set($key . 'flag', 1, $wait_reset_seconds);
26-
$this->cur_requests = $cur_requests;
27-
return true;
28-
}
2920
$this->cur_requests = $cur_requests;
21+
3022
if ($cur_requests < $max_requests) { // 允许访问
31-
$cache->inc($key);
23+
$cache->set($key, $this->cur_requests + 1, $wait_reset_seconds);
3224
return true;
3325
}
3426

0 commit comments

Comments
 (0)