ShouldThrottle.php
3.0 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
<?php
namespace Yansongda\Supports\Traits;
use Predis\Client;
/**
* Trait ShouldThrottle.
*
* @property Client $redis
*/
trait ShouldThrottle
{
/**
* _throttle.
*
* @var array
*/
protected $_throttle = [
'limit' => 60,
'period' => 60,
'count' => 0,
'reset_time' => 0,
];
/**
* isThrottled.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $key
* @param int $limit
* @param int $period
* @param bool $auto_add
*
* @return bool
*/
public function isThrottled($key, $limit = 60, $period = 60, $auto_add = false)
{
if (-1 === $limit) {
return false;
}
$now = microtime(true) * 1000;
$this->redis->zremrangebyscore($key, 0, $now - $period * 1000);
$this->_throttle = [
'limit' => $limit,
'period' => $period,
'count' => $this->getThrottleCounts($key, $period),
'reset_time' => $this->getThrottleResetTime($key, $now),
];
if ($this->_throttle['count'] < $limit) {
if ($auto_add) {
$this->throttleAdd($key, $period);
}
return false;
}
return true;
}
/**
* 限流 + 1.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $key
* @param int $period
*/
public function throttleAdd($key, $period = 60)
{
$now = microtime(true) * 1000;
$this->redis->zadd($key, [$now => $now]);
$this->redis->expire($key, $period * 2);
}
/**
* getResetTime.
*
* @author yansongda <me@yansongda.cn>
*
* @param $key
* @param $now
*
* @return int
*/
public function getThrottleResetTime($key, $now)
{
$data = $this->redis->zrangebyscore(
$key,
$now - $this->_throttle['period'] * 1000,
$now,
['limit' => [0, 1]]
);
if (0 === count($data)) {
return $this->_throttle['reset_time'] = time() + $this->_throttle['period'];
}
return intval($data[0] / 1000) + $this->_throttle['period'];
}
/**
* 获取限流相关信息.
*
* @author yansongda <me@yansongda.cn>
*
* @param string|null $key
* @param mixed|null $default
*
* @return array|null
*/
public function getThrottleInfo($key = null, $default = null)
{
if (is_null($key)) {
return $this->_throttle;
}
if (isset($this->_throttle[$key])) {
return $this->_throttle[$key];
}
return $default;
}
/**
* 获取已使用次数.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $key
* @param int $period
*
* @return string
*/
public function getThrottleCounts($key, $period = 60)
{
$now = microtime(true) * 1000;
return $this->redis->zcount($key, $now - $period * 1000, $now);
}
}