Created
November 13, 2016 06:40
-
-
Save qianlongzt/e8acda631420a155a37ffc233b18efb9 to your computer and use it in GitHub Desktop.
php 通过redis限制速度
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
<?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