iami233
iami233
文章153
标签38
分类4

文章分类

文章归档

使用 Redis 限制访问次数

使用 Redis 限制访问次数

最近在写 Ten·API 的新后台,打算限制一下用户的日请求数,所以简单学了一下Redis,每个自然日(0时-24时)限制请求 1000 次。

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
40
41
42
43
44
45
46
<?php
<?php
/**
* title: Redis请求限制
* update: 2024-05-03
* author: iami233
*/
date_default_timezone_set('PRC'); // 指定时区为中国

// 连接数据库
$db = new PDO('mysql:host=localhost;dbname=your_database_name', 'username', 'password');

// 获取token
$token = filter_input(INPUT_GET, 'token');
if (!$token) {
die("请传递Token");
}

// 从数据库验证token
$query = $db->prepare("SELECT COUNT(*) FROM table WHERE token = ?");
$query->execute([$token]);
if ($query->fetchColumn() == 0) {
die("无效的Token");
}

// 连接Redis
$redis = new Redis();
if (!$redis->connect('127.0.0.1', 6379)) {
die("无法连接到Redis");
}

// 设置或更新请求计数
$requestsLimit = 1000; // 每天最大请求次数
$requestsCount = $redis->incr($token);
if ($requestsCount === 1) {
// 初次设置时,设定过期时间至第二天0点
$expiresAt = strtotime('tomorrow');
$redis->expireAt($token, $expiresAt);
}

// 检查请求次数是否超过限制
if ($requestsCount > $requestsLimit) {
echo "次数用尽,已达到上限{$requestsCount}次";
} else {
echo "已经调用{$requestsCount}次";
}
本文作者:iami233
本文链接:https://5ime.cn/redis-request.html
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可