PHP菜鸟博客_共同学习分享PHP技术心得【PHP爱好者】
php+redis实现接口限制频率
2022-12-12 菜鸟站长
<?php

header("Access-Control-Allow-Origin:*");

header('Access-Control-Allow-Methods:*');  

//函数

function api_frequency_visits($uid)

{

    //时间内最大访问次数

    $max_frequency = 10;

    //限制时间

    $limit_time = 60;

    //当前时间

    $now_time = time();

    $key = "user:{$uid}:api:frequency";

    $redis = new Redis();

    $redis->connect('127.0.0.1');

    $redis->auth('********');

    $data = $redis->hGetAll($key);

    //需要删除的key

    $del_key = [];

    //时间内访问的总次数

    $total = 0;

    foreach ($data as $time=>$count) {

        if ($time < $now_time - $limit_time) {

            $del_key[] = $time;

        } else {

            $total += $count;

        }

    }



    //存在需要删除的key

    if ($del_key) {

        $redis->hDel($key, ...$del_key);

    }

    if ($total >= $max_frequency) {

        return false;

    }

    return $redis->hIncrBy($key, $now_time, 1);

}







//具体业务逻辑处理,uid可以是应用,也可以是ip,客户的一个标志

$uid = $_GET['id'];

$result = api_frequency_visits($uid);



if (!$result) {

    echo json_encode(['code'=>0, 'msg'=>'操作过于频繁', 'data'=>[]], JSON_UNESCAPED_UNICODE);

    die;

}

echo json_encode(['code'=>1, 'msg'=>'', 'data'=>['uid'=>$uid,'other'=>rand()]], JSON_UNESCAPED_UNICODE);die;




发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容