Created
December 30, 2015 13:32
-
-
Save z1nkum/cfe8bad825a0554b8ed2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Redis Ratelimit trait | |
*/ | |
trait RateLimitRedis | |
{ | |
protected $redis; | |
protected function connectRedis() { | |
try { | |
$this->redis = new \Predis\Client(); | |
} catch (\Exception $e) { | |
throw new AjaxException( 'Ошибка соединения с Redis' ); | |
} | |
} | |
protected function checkRateLimit( $key, $limit, $period ) { | |
if ( ! $this->redis instanceof \Predis\Client ) $this->connectRedis(); | |
if ( $this->redis->exists($key) ) { | |
$this->redis->incr($key); | |
$value = $this->redis->get($key); | |
if ( $value > $limit) throw new AjaxException("Превышена частота обращения к API. Доступ временно ограничен", "$key val: $value (limit $limit)"); | |
} else { | |
$this->redis->set($key, 1); | |
$this->redis->expire($key, $period); | |
} | |
} | |
protected function setRedisKeyValTTL ($key, $val, $ttl) { | |
try { | |
$this->redis->set($key, $val); | |
$this->redis->expire($key, $ttl); | |
} catch (\Exception $e) { | |
throw new AjaxException( 'Ошибка добавления ключа в REDIS' ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment