Skip to content

Instantly share code, notes, and snippets.

@z1nkum
Created December 30, 2015 13:32
Show Gist options
  • Save z1nkum/cfe8bad825a0554b8ed2 to your computer and use it in GitHub Desktop.
Save z1nkum/cfe8bad825a0554b8ed2 to your computer and use it in GitHub Desktop.
/*
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