Skip to content

Instantly share code, notes, and snippets.

@qianlongzt
Created November 13, 2016 06:40
Show Gist options
  • Save qianlongzt/e8acda631420a155a37ffc233b18efb9 to your computer and use it in GitHub Desktop.
Save qianlongzt/e8acda631420a155a37ffc233b18efb9 to your computer and use it in GitHub Desktop.
php 通过redis限制速度
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$time = $_SERVER['REQUEST_TIME'];
$maxPerSecond = 10;
try {
$redis = new Redis();
$redis -> connect('127.0.0.1', 6379, 20);
$redis -> lpush($ip, $time);
if(
($redis -> llen ($ip) >= $maxPerSecond) && ($redis -> lrange($ip, $maxPerSecond - 1, $maxPerSecond - 1))[0] + 1 >= $time
) {
//sleep(3);
echo 'request too much';
} else {
echo 'normal';
}
$redis -> ltrim($ip, 0, $maxPerSecond - 1);
} catch(Exception $e) {
echo $e -> getMessage();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment