Api接口速率限制,防止接口被频繁请求。

代码实现

使用 cache记录请求情况,进行判断。

<?php
public static function checkFreq($cacheKey, $second_limit = 60, $count_limit = 30)
{
    $cache = Cache::instance();
    if (is_array($cacheKey)){
        sort($cacheKey, SORT_STRING);
        $cacheKey = join('', $cacheKey);
    }
    $res = $cache->get($cacheKey);

    $timestamp = time();
    if (!$res || $timestamp - $res['timestamp'] > $second_limit){
        $res = array(
            'count' => 1,
            'timestamp' => $timestamp
        );
        $cache->set($cacheKey, $res, $second_limit);
        return true;
    }

    if ($res['count'] < $count_limit){
        $res['count']++;
        $cache->set($cacheKey, $res, $second_limit);
        return true;
    }else{
        return false;
    }
}
    
$func_name = 'b0109_gensmart_annotate_sequence';
if (false === api::checkFreq(array(
        #'ip' => Request::$client_ip,
        'cust_no' => $this->cust_no,
        'func_name' => $func_name,
    ), 10, 3)){
    $return_struct['msg'] = __('API_REQUEST_FREQUENT');
    echo json_encode($return_struct);exit;
}