用 Redis 限制访问频率

线上生产环境中不免会有一些代码会频繁进行数据库操作,然后就会有那种无聊的人用这种方式频繁请求你的接口,导致服务被请求到死,500的绝望。

为了避免这种问题,一个是使用lua脚本与nginx相结合,来实现访问请求限制,另一种方法就是使用PHP和Redis啦。

下面的脚本实现了一个简易却十分有效的请求限制功能 代码来源

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php

require('predis/src/Autoloader.php');

$redis = new Predis\Client(array(
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => '6379'
));

$redis->auth('123456');

//这个key记录该用户1的访问次数
$key = 'user:1:api_count';

//限制次数为10
$limit = 10;

$check = $redis->exists($key);
if($check){
$redis->incr($key);
$count = $redis->get($key);
if($count > 10){
exit('your have too many request');
}
}else{
$redis->incr($key);
//限制时间为60秒
$redis->expire($key,60);
}

$count = $redis->get($key);
echo 'You have '.$count.' request';

//......
//API业务逻辑
echo '<br/>';
echo 'Hello,World!This is the api content.';
?>
Author

Jason

Posted on

08/06/17

Updated on

10/12/20

Licensed under

Comments

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×