检查/设置用户访问频率

浏览:2419 发布日期:2015/06/18 分类:业务逻辑 关键字: 访问频率控制 Redis
* 检查/设置用户访问频率 指定 user_marked在 time_slot 毫秒内最多访问 count次;
* 例如 check_rate_limiting(2000,1, 'plan:'.$plan_id); // 2秒钟之内只允许1次投标
/**
 * 检查/设置用户访问频率 指定 user_marked在 time_slot 毫秒内最多访问 count次;
 * 例如 check_rate_limiting(2000,1, 'plan:'.$plan_id); //  2秒钟之内只允许1次投标
 *
 * @param $lime_slot 时间片 单位毫秒
 * @param $count 整数
 * @param $user_marked 用户唯一标示,默认为客户端IP
 *
 * @return array('status'=>1,'info'=>'')
 * @author leeyi <leeyisoft@qq.com> @2015-12-01 17:22:45
 */
function check_rate_limiting($time_slot, $count, $user_marked = '')
{
    $user_marked = empty($user_marked) ? get_client_ip() : $user_marked;
    $cache_key = 'rate.limiting:'.$user_marked;

    $redis = new \Redis;
    $millisecond = intval(microtime(true)*1000);

    $redis->handler->pexpire($cache_key, $time_slot); // 设置过期时间
    $list_len = $redis->handler->llen($cache_key);
    $ret = array('status'=>1, 'info'=>'');
    if ($list_len<$count) {
        $redis->handler->lpush($cache_key, $millisecond);
        $ret['status'] = 1;
    } else {
        $last_millisecond = $redis->handler->lindex($cache_key, -1); // -1 标示列表最后一个元素
        if (($millisecond-$last_millisecond)<$time_slot) {
            $ret['status'] = 0;
            $ret['info'] = '访问频率超过了限制,请稍后重试。';
        } else {
            $redis->handler->lpush($cache_key, $millisecond);
            $redis->handler->ltrim($cache_key, 0, $count-1);
            $ret['status'] = 1;
        }
    }
    1==$ret['status'] && $ret['info'] = $list_len+1;
    return $ret;
}
评论( 相关
后面还有条评论,点击查看>>