12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- <?php
- declare(strict_types=1);
- namespace catcher\library\rate;
- use catcher\exceptions\FailedException;
- class GrantLimit
- {
- use Redis;
- protected $ttl = 60;
- protected $limit = 1000;
- protected $key;
- public function __construct($key)
- {
- $this->key = $key;
- $this->init();
- }
-
- public function overflow()
- {
- if ($this->getCurrentVisitTimes() > $this->limit) {
- throw new FailedException('访问限制');
- }
- $this->inc();
- }
-
- public function inc()
- {
- $this->getRedis()->incr($this->key);
- }
-
- protected function init()
- {
- if (!$this->getRedis()->exists($this->key)) {
- $this->getRedis()->setex($this->key, $this->ttl, 0);
- }
- }
-
- protected function getCurrentVisitTimes()
- {
- return $this->getRedis()->get($this->key);
- }
- }
|