4

使用Reids限制访问次数

 3 years ago
source link: https://5ime.cn/redis-request.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
使用Reids限制访问次数

使用Reids限制访问次数

最近在写 Ten·API 的新后台,打算限制一下用户的日请求数,所以简单学了一下Redis,每个自然日(0时-24时)限制请求1000次。数据库基本返回的都是Array,所以可以用PHP内置函数in_array来判断token是否存在数组内,达到验证的目的。

<?php
/**
 * title: Redis请求限制
 * author: iami233
 */
date_default_timezone_set('PRC');
// 指定时区
$token = @$_REQUEST['token'];
// $data = Db::name('table')->column('token');
// if(isset($token) && in_array($token,$data))
if(isset($token)){
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379); 
    // 连接 Redis
    if (!$redis->exists($token)){
        // 判断是否为初次访问
        $tomorrow = strtotime('tomorrow');
        // 获取第二天0点的时间戳
        $time = $tomorrow-time();
        $redis->set($token,1,$time);
        // 初始次数设置为1,过期时间设置为第二天0点
    }else{
        if ($redis->get($token) < 1000){ 
            // 判断是否达到请求上限(每日请求需小于1000次)
            $redis->incr($token); 
            // 请求次数加一
            $get_num = $redis->get($token);
            echo '已经调用'.$get_num.'次';
        }else{
            echo '次数用尽,已达到上限'.$redis->get($token).'次';
        }
    }
}else{
    echo "请传递Token";
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK