nginx限制请求数(ngx_http_limit_req_module) 实现详解

17 篇文章 1 订阅
6 篇文章 0 订阅

   nginx ngx_http_limit_req_module可以实现限制请求IP单位时间内的请求次数的作用。限制请求数能一定程度上降低nginx以及nginx作为代理时对恶意的请求访问压力。同时,对于非恶意的高频率请求,一定程度上降低了nginx或者后端服务器的负载。
  nginx为了实现对请求IP进行请求限制的功能,需要能做到对请求IP已经对应时间段的请求次数进行保存及高效的查找判断。由于nginx采用的是多进程的架构,因此,需要将这些信息保存在共享内存中,以便于所有的worker进程均能获知这些信息;而且,为了能达到高效地将对这些信息进行检索及管理,nginx使用了红黑树作为处理这些信息的数据结构。
  接下来是对ngx_http_limit_req_module模块中的数据结构进行描述说明

1.ngx_http_limit_req_module红黑树节点

typedef struct {
    u_char                       color;      //红黑树节点的颜色值
    u_char                       dummy;      //这里是一个空值 不代表任何含义
    u_short                      len;        //节点key值的长度 这里是可变的值跟配置的key值相关
    ngx_queue_t                  queue;      //LRU队列(对过期的节点进行淘汰清理的队列)
    ngx_msec_t                   last;       //最新访问节点的时间
    /* integer value, 1 corresponds to 0.001 r/s */
    ngx_uint_t                   excess;     //超出设置请求次数值的差值
    ngx_uint_t                   count;      //请求次数计数器
    u_char                       data[1];    //节点key值的数据(和len共同作用)
} ngx_http_limit_req_node_t

2.ngx_http_limit_req_module红黑树

typedef struct {
    ngx_rbtree_t                  rbtree;    //红黑树
    ngx_rbtree_node_t             sentinel;  //红黑树的哨兵节点
    ngx_queue_t                   queue;     //LRU队列(作用和1的描述的相同)
} ngx_http_limit_req_shctx_t;

3.ngx_http_limit_req_module限制请求的上下文结构

typedef struct {
    ngx_http_limit_req_shctx_t  *sh;                //在2中描述的结构
    ngx_slab_pool_t             *shpool;            //slab算法分配共享内存的内存池
    /* integer value, 1 corresponds to 0.001 r/s */
    ngx_uint_t                   rate;              //频率用整形来表示浮点 请求频率
    ngx_http_complex_value_t     key;               //配置文件中配置的限制请求变量(一般是请求IP)
    ngx_http_limit_req_node_t   *node;              //红黑树节点(代表当前处理的节点)
} ngx_http_limit_req_ctx_t

4.限制请求的配置描述结构(可以配置多个)

typedef struct {
    ngx_shm_zone_t              *shm_zone;          //共享内存描述
    /* integer value, 1 corresponds to 0.001 r/s */
    ngx_uint_t                   burst;             //同时超过请求允许频率的请求数量
    ngx_uint_t                   nodelay; /* unsigned  nodelay:1 */ //是否将请求进行延时
} ngx_http_limit_req_limit_t

5.location级别的限制请求配置

typedef struct {
    ngx_array_t                  limits;             //所有location配置的4结构描述 放在数组中
    ngx_uint_t                   limit_log_level;    //设置限制请求的日志级别
    ngx_uint_t                   delay_log_level;    //设置延时处理请求的日志级别
    ngx_uint_t                   status_code;      //设置达到设置请求限制条件或者处理出错的响应给请求端的状态码
} ngx_http_limit_req_conf_t

  nginx请求限制模块可以配置全局(main级别)的请求限制 里面可以配置共享内存的容量、请求的频率单位时间内的请求次数(秒级或者分级)。main级别的配置会对各个location级别的配置产生影响,首先会判断main级别设置的限制条件,其次会判断location级别设置的限制条件。

  main级别的的配置处理流程如下:

static char *
ngx_http_limit_req_zone(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
    ...
    value = cf->args->elts; //这里是配置的描述

    /*为3中的上下文结构分配内存*/
    ctx = ngx_pcalloc(cf->pool, sizeof(ngx_http_limit_req_ctx_t));
    if (ctx == NULL) {
        return NGX_CONF_ERROR;
    }

    ngx_memzero(&ccv, sizeof(ngx_http_compile_complex_value_t));
    ...    
    /*
    设置main级别配置的key值变量 这里的key值变量在处理请求的时候会产生真正的值 
    key值是作为查找和插入红黑树节点信息的key值
    */
    if (ngx_http_compile_complex_value(&ccv) != NGX_OK) {
        return NGX_CONF_ERROR;
    }
    ...
    for (i = 2; i < cf->args->nelts; i++) {

        if (ngx_strncmp(value[i].data, "zone=", 5) == 0) {
           /*这里是配置红黑树zone的信息*/

            name.data = value[i].data + 5;

            p = (u_char *) ngx_strchr(name.data, ':');

            if (p == NULL) {
                ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                                   "invalid zone size \"%V\"", &value[i]);
                return NGX_CONF_ERROR;
            }
            /*name是共享内存的名称*/
            name.len = p - name.data;

            s.data = p + 1;
            s.len = value[i].data + value[i].len - s.data;
            /*这里取得了配置共享内存的大小*/
            size = ngx_parse_size(&s);

            if (size == NGX_ERROR) {
                /*解析配置大小信息出错*/
                ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                                   "invalid zone size \"%V\"", &value[i]);
                return NGX_CONF_ERROR;
            }

            if (size < (ssize_t) (8 * ngx_pagesize)) {
                /*配置的共享内存的大小不得小于系统页大小的8倍*/
                ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                                   "zone \"%V\" is too small", &value[i]);
                return NGX_CONF_ERROR;
            }

            continue;
        }

        if (ngx_strncmp(value[i].data, "rate=", 5) == 0) {
            /*这里是配置限制请求频率*/

            len = value[i].len;
            p = value[i].data + len - 3;

            if (ngx_strncmp(p, "r/s", 3) == 0) {
                /*请求频率的单位是秒*/
                scale = 1;
                len -= 3;

            } else if (ngx_strncmp(p, "r/m", 3) == 0) {
               /*请求频率的单位是分钟*/
                scale = 60;
                len -= 3;
            }

            rate = ngx_atoi(value[i].data + 5, len - 5);
            if (rate <= 0) {
                ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                                   "invalid rate \"%V\"", &value[i]);
                return NGX_CONF_ERROR;
            }

            continue;
        }

        ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                           "invalid parameter \"%V\"", &value[i]);
        return NGX_CONF_ERROR;
    }

    if (name.len == 0) {
        ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                           "\"%V\" must have \"zone\" parameter",
                           &cmd->name);
        return NGX_CONF_ERROR;
    }
    /*设置了请求频率 这里放大了1000倍 是为了取整*/
    ctx->rate = rate * 1000 / scale;
    /*添加共享内存*/
    shm_zone = ngx_shared_memory_add(cf, &name, size,
                                     &ngx_http_limit_req_module);
    if (shm_zone == NULL) {
        return NGX_CONF_ERROR;
    }

    if (shm_zone->data) {
        ctx = shm_zone->data;

        ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                           "%V \"%V\" is already bound to key \"%V\"",
                           &cmd->name, &name, &ctx->key.value);
        return NGX_CONF_ERROR;
    }
    /*设置共享内存初始化函数*/
    shm_zone->init = ngx_http_limit_req_init_zone;
    shm_zone->data = ctx;

    return NGX_CONF_OK;
}

   location级别的配置处理流程 可以为多个server进行配置

static char *
ngx_http_limit_req(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
    ngx_http_limit_req_conf_t  *lrcf = conf;
    ...
    value = cf->args->elts;

    shm_zone = NULL;
    burst = 0;
    nodelay = 0;

    for (i = 1; i < cf->args->nelts; i++) {

        if (ngx_strncmp(value[i].data, "zone=", 5) == 0) {
            /*配置的共享内存 注意这里的共享内存是在上面的main级别中配置过的*/
            s.len = value[i].len - 5;
            s.data = value[i].data + 5;

            shm_zone = ngx_shared_memory_add(cf, &s, 0,
                                             &ngx_http_limit_req_module);
            if (shm_zone == NULL) {
                return NGX_CONF_ERROR;
            }

            continue;
        }

        if (ngx_strncmp(value[i].data, "burst=", 6) == 0) {
           /*同时超过请求允许频率的请求数量*/

            burst = ngx_atoi(value[i].data + 6, value[i].len - 6);
            if (burst <= 0) {
                ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                                   "invalid burst rate \"%V\"", &value[i]);
                return NGX_CONF_ERROR;
            }

            continue;
        }
        /*是否使用nodelay 使用nodelay则不会延时处理超出限制的请求 请求端得到的就是403状态响应*/
        if (ngx_strcmp(value[i].data, "nodelay") == 0) {
            nodelay = 1;
            continue;
        }

        ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                           "invalid parameter \"%V\"", &value[i]);
        return NGX_CONF_ERROR;
    }

    if (shm_zone == NULL) {
        /*共享内存为空 说明没有配置共享内存 报错*/
        ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                           "\"%V\" must have \"zone\" parameter",
                           &cmd->name);
        return NGX_CONF_ERROR;
    }

    limits = lrcf->limits.elts;

    if (limits == NULL) {
       /*第一次配置location级别的限制 先进行数组的初始化*/
        if (ngx_array_init(&lrcf->limits, cf->pool, 1,
                           sizeof(ngx_http_limit_req_limit_t))
            != NGX_OK)
        {
            return NGX_CONF_ERROR;
        }
    }

    for (i = 0; i < lrcf->limits.nelts; i++) {
      /*这里会检查location级别的共享内存是否出现了重复*/
        if (shm_zone == limits[i].shm_zone) {
            return "is duplicate";
        }
    }
    /*添加一个location级别的location配置*/
    limit = ngx_array_push(&lrcf->limits);
    if (limit == NULL) {
        return NGX_CONF_ERROR;
    }

    limit->shm_zone = shm_zone;
    /*放大1000倍*/
    limit->burst = burst * 1000;
    limit->nodelay = nodelay;

    return NGX_CONF_OK;
}

main级别的共享内存初始化

static ngx_int_t
ngx_http_limit_req_init_zone(ngx_shm_zone_t *shm_zone, void *data)
{
    ngx_http_limit_req_ctx_t  *octx = data;
    ...
    ctx = shm_zone->data;

    if (octx) {
        /*main级别配置时设置的参数 这里先用key值做了比较*/
        if (ctx->key.value.len != octx->key.value.len
            || ngx_strncmp(ctx->key.value.data, octx->key.value.data,
                           ctx->key.value.len)
               != 0)
        {
            ngx_log_error(NGX_LOG_EMERG, shm_zone->shm.log, 0,
                          "limit_req \"%V\" uses the \"%V\" key "
                          "while previously it used the \"%V\" key",
                          &shm_zone->shm.name, &ctx->key.value,
                          &octx->key.value);
            return NGX_ERROR;
        }

        ctx->sh = octx->sh;
        ctx->shpool = octx->shpool;

        return NGX_OK;
    }
    /*slab内存池分配器的地址设置成共享内存的地址 用户态地址到共享内存地址的绑定设置*/
    ctx->shpool = (ngx_slab_pool_t *) shm_zone->shm.addr;

    if (shm_zone->shm.exists) {
       /*共享内存已经设置过了,直接返回*/
        ctx->sh = ctx->shpool->data;

        return NGX_OK;
    }
    /*为shpool(slab分配器内存池指针) 分配内存*/
    ctx->sh = ngx_slab_alloc(ctx->shpool, sizeof(ngx_http_limit_req_shctx_t));
    if (ctx->sh == NULL) {
        return NGX_ERROR;
    }

    ctx->shpool->data = ctx->sh;
    /*初始化红黑树 并设置红黑树节点的插入处理函数*/
    ngx_rbtree_init(&ctx->sh->rbtree, &ctx->sh->sentinel,
                    ngx_http_limit_req_rbtree_insert_value);
    /*初始化LRU队列*/
    ngx_queue_init(&ctx->sh->queue);

    len = sizeof(" in limit_req zone \"\"") + shm_zone->shm.name.len;
    /*为日志上下文结构分配内存*/
    ctx->shpool->log_ctx = ngx_slab_alloc(ctx->shpool, len);
    if (ctx->shpool->log_ctx == NULL) {
        return NGX_ERROR;
    }

    ngx_sprintf(ctx->shpool->log_ctx, " in limit_req zone \"%V\"%Z",
                &shm_zone->shm.name);

    ctx->shpool->log_nomem = 0;

    return NGX_OK;
}

  以下是ngx_http_limit_req_module的处理流程
1.挂载http处理pre_access处理函数指针

static ngx_int_t
ngx_http_limit_req_init(ngx_conf_t *cf)
{
    ngx_http_handler_pt        *h;
    ngx_http_core_main_conf_t  *cmcf;

    cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);
    /*添加pre_access处理函数指针*/
    h = ngx_array_push(&cmcf->phases[NGX_HTTP_PREACCESS_PHASE].handlers);
    if (h == NULL) {
        return NGX_ERROR;
    }
    /*将函数指针设置为ngx_http_limit_req_module的处理函数*/
    *h = ngx_http_limit_req_handler;

    return NGX_OK;
}

2.在pre_access阶段触发处理函数 这里就会进行配置的限制判断和处理

static ngx_int_t
ngx_http_limit_req_handler(ngx_http_request_t *r)
{
...
    /*请求已经被标记为请求限制 直接返回decline 拒绝进行后续的http处理流程*/
    if (r->main->limit_req_set) {
        return NGX_DECLINED;
    }

    lrcf = ngx_http_get_module_loc_conf(r, ngx_http_limit_req_module);
    /*取得location级别的限制数组*/
    limits = lrcf->limits.elts;

    excess = 0;

    rc = NGX_DECLINED;

#if (NGX_SUPPRESS_WARN)
    limit = NULL;
#endif

    for (n = 0; n < lrcf->limits.nelts; n++) {
        /*
        这里会遍历配置的限制数组(即ngx_http_limit_req_limit_t数组)

        */

        limit = &limits[n];

        ctx = limit->shm_zone->data;

        if (ngx_http_complex_value(r, &ctx->key, &key) != NGX_OK) {
            /*编译key值变量 得到真正的key值*/
            return NGX_HTTP_INTERNAL_SERVER_ERROR;
        }

        if (key.len == 0) {
            /*key是空的 跳过*/
            continue;
        }

        if (key.len > 65535) {
            /*得到的key过长 跳过*/
            ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
                          "the value of the \"%V\" key "
                          "is more than 65535 bytes: \"%V\"",
                          &ctx->key.value, &key);
            continue;
        }
        /*用key值计算得到hash值*/
        hash = ngx_crc32_short(key.data, key.len);

        ngx_shmtx_lock(&ctx->shpool->mutex);
        /*这里会进行红黑树的查找及插入 */
        rc = ngx_http_limit_req_lookup(limit, hash, &key, &excess,
                                       (n == lrcf->limits.nelts - 1));

        ngx_shmtx_unlock(&ctx->shpool->mutex);

        ngx_log_debug4(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                       "limit_req[%ui]: %i %ui.%03ui",
                       n, rc, excess / 1000, excess % 1000);

        if (rc != NGX_AGAIN) {
        //无需重试 直接跳出
            break;
        }
    }

    if (rc == NGX_DECLINED) {
      /*没有设置location级别的请求限制 直接返回decline*/
        return NGX_DECLINED;
    }
    /*主请求标记 为已经设置过限制*/
    r->main->limit_req_set = 1;

    if (rc == NGX_BUSY || rc == NGX_ERROR) {
       /*前面处理出错或者达到了限制的条件 */

        if (rc == NGX_BUSY) {
            /*达到了限制条件 这里会在日志里进行打印*/
            ngx_log_error(lrcf->limit_log_level, r->connection->log, 0,
                          "limiting requests, excess: %ui.%03ui by zone \"%V\"",
                          excess / 1000, excess % 1000,
                          &limit->shm_zone->shm.name);
        }

        while (n--) {
            /*得到每一个location的限制上下文*/
            ctx = limits[n].shm_zone->data;
            /*
             发现上下文中的红黑树节点是空的 跳过
             node正常情况下会从ngx_http_limit_req_lookup函数中得到设置得到
            */
            if (ctx->node == NULL) {
                continue;
            }
            /*由于需要改变共享内存中红黑树节点的属性(计数) 用于同步worker进程 加锁*/
            ngx_shmtx_lock(&ctx->shpool->mutex);
            //减少一次node计数
            ctx->node->count--;

            ngx_shmtx_unlock(&ctx->shpool->mutex);
            /*将请求限制的node指针置为空 请求限制上下文就是ngx_http_limit_req_ctx_t*/
            ctx->node = NULL;
        }

        return lrcf->status_code; //返回nginx配置文件中配置的状态码
    }
    /*上面的处理是达到了设置限制的条件*/

    /* rc == NGX_AGAIN || rc == NGX_OK */

    if (rc == NGX_AGAIN) {
        excess = 0;
    }

    /*
        计算得到需要的延时时间
    */
    delay = ngx_http_limit_req_account(limits, n, &excess, &limit);

    /*
      无法进行延时(配置了no_delay或者没有剩余的请求次数) 直接返回decline
    */
    if (!delay) {
        return NGX_DECLINED;
    }

    ngx_log_error(lrcf->delay_log_level, r->connection->log, 0,
                  "delaying request, excess: %ui.%03ui, by zone \"%V\"",
                  excess / 1000, excess % 1000, &limit->shm_zone->shm.name);
    /*处理读事件*/
    if (ngx_handle_read_event(r->connection->read, 0) != NGX_OK) {

        return NGX_HTTP_INTERNAL_SERVER_ERROR;
    }
    /*设置读写事件处理函数*/
    r->read_event_handler = ngx_http_test_reading;
    r->write_event_handler = ngx_http_limit_req_delay;
    /*写事件延时标志设置*/
    r->connection->write->delayed = 1;
    /*增加一个写事件的延时定时器*/
    ngx_add_timer(r->connection->write, delay);

    return NGX_AGAIN;
}

延时写事件处理函数

static void
ngx_http_limit_req_delay(ngx_http_request_t *r)
{
    ngx_event_t  *wev;

    ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                   "limit_req delay");

    wev = r->connection->write;

    if (wev->delayed) {
           /*处理写事件*/
        if (ngx_handle_write_event(wev, 0) != NGX_OK) {
            ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
        }

        return;
    }
    /*处理读事件*/
    if (ngx_handle_read_event(r->connection->read, 0) != NGX_OK) {
        ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
        return;
    }
    /*重新设置读写事件处理函数*/
    r->read_event_handler = ngx_http_block_reading;
    r->write_event_handler = ngx_http_core_run_phases;
    /*处理http请求 这里又会触发到pre_access等等的配置的函数*/
    ngx_http_core_run_phases(r);
}

红黑树查询及插入的处理

static ngx_int_t
ngx_http_limit_req_lookup(ngx_http_limit_req_limit_t *limit, ngx_uint_t hash,
    ngx_str_t *key, ngx_uint_t *ep, ngx_uint_t account)
{
    //获取当前的时间
    now = ngx_current_msec;
    //获得限制的上下文
    ctx = limit->shm_zone->data;

    node = ctx->sh->rbtree.root;
    sentinel = ctx->sh->rbtree.sentinel;

    while (node != sentinel) {

        if (hash < node->key) {
           /*查找红黑树的左节点*/
            node = node->left;
            continue;
        }

        if (hash > node->key) {
            /*查找红黑树的右节点*/
            node = node->right;
            continue;
        }

        /* hash == node->key */

        lr = (ngx_http_limit_req_node_t *) &node->color;
        /*比较key值*/
        rc = ngx_memn2cmp(key->data, lr->data, key->len, (size_t) lr->len);

        if (rc == 0) {
            /*找到了 更新LRU*/
            ngx_queue_remove(&lr->queue);
            ngx_queue_insert_head(&ctx->sh->queue, &lr->queue);
            /*取得当前和最新一次的时间差*/
            ms = (ngx_msec_int_t) (now - lr->last);
            /*计算超出的值*/
            excess = lr->excess - ctx->rate * ngx_abs(ms) / 1000 + 1000;

            if (excess < 0) {
            //超过的值小于0 设置为0
                excess = 0;
            }

            *ep = excess;

            if ((ngx_uint_t) excess > limit->burst) {
               //超过的值超过了设置的阈值 返回busy
                return NGX_BUSY;
            }

            if (account) { //到了最后最后一个location级别限制数组
               /*更新超出的值以及最近的访问时间*/
                lr->excess = excess;
                lr->last = now;
                return NGX_OK;
            }

            lr->count++; //访问的次数增加

            ctx->node = lr; //更新限制的上下文的node

            return NGX_AGAIN;
        }

        node = (rc < 0) ? node->left : node->right;
    }

    *ep = 0;
    /*
    计算所要分配的内存大小 color的字节数+ data的字节数+key值长度的字节数
    */
    size = offsetof(ngx_rbtree_node_t, color)
           + offsetof(ngx_http_limit_req_node_t, data)
           + key->len;
    /*这里会淘汰一个LRU队列的头部节点*/
    ngx_http_limit_req_expire(ctx, 1);

    node = ngx_slab_alloc_locked(ctx->shpool, size);

    if (node == NULL) {
       /*共享内存不足 会多淘汰几个LRU节点(这里是3个)*/
        ngx_http_limit_req_expire(ctx, 0);
        //再次尝试从共享内存中分配内存
        node = ngx_slab_alloc_locked(ctx->shpool, size);
        if (node == NULL) {
            /*分配内存失败 错误会打印到日志中 并且返回错误*/
            ngx_log_error(NGX_LOG_ALERT, ngx_cycle->log, 0,
                          "could not allocate node%s", ctx->shpool->log_ctx);
            return NGX_ERROR;
        }
    }
    //设置红黑树节点的key值
    node->key = hash;
    //得到color
    lr = (ngx_http_limit_req_node_t *) &node->color;
    //设置key值的长度以及初始化超出值
    lr->len = (u_short) key->len;
    lr->excess = 0;
    //拷贝key值
    ngx_memcpy(lr->data, key->data, key->len);
    //将创建的节点插入到红黑树
    ngx_rbtree_insert(&ctx->sh->rbtree, node);
    //将节点的标记到LRU队列的头部
    ngx_queue_insert_head(&ctx->sh->queue, &lr->queue);

    if (account) {
        lr->last = now;
        lr->count = 0;
        return NGX_OK;
    }

    lr->last = 0;
    /*标记已经使用过一次了*/
    lr->count = 1;
    /*设置请求限制上下文的节点*/
    ctx->node = lr;

    return NGX_AGAIN;
}

计算取得http处理延时的时间

static ngx_msec_t
ngx_http_limit_req_account(ngx_http_limit_req_limit_t *limits, ngx_uint_t n,
    ngx_uint_t *ep, ngx_http_limit_req_limit_t **limit)
{
    ...
    excess = *ep; //得到超出值

    if (excess == 0 || (*limit)->nodelay) {
        //已经没有超出值剩余或者没有location配置了nodelay(意味着想立即处理) 
        /*设置最大的延时值为0*/
        max_delay = 0;

    } else {
        /*得到限制的上下文*/
        ctx = (*limit)->shm_zone->data;
        /*用计算得到的请求频率(注意由于取整被放大了1000倍) 以及剩余的值来算出最长的延时时间(毫秒)*/
        max_delay = excess * 1000 / ctx->rate;
    }

    while (n--) {
        /*取得location配置的上下文限制信息*/
        ctx = limits[n].shm_zone->data;
        /*取得红黑树节点*/
        lr = ctx->node;

        if (lr == NULL) {
          /*红黑树节点为空 跳过*/
            continue;
        }

        ngx_shmtx_lock(&ctx->shpool->mutex); 
        /*加锁 设置节点的信息/

        /*取得时间差*/
        now = ngx_current_msec;
        ms = (ngx_msec_int_t) (now - lr->last);
        /*获得剩余的请求数量*/
        excess = lr->excess - ctx->rate * ngx_abs(ms) / 1000 + 1000;

        if (excess < 0) {
            /*这里的剩余值不得小于0*/
            excess = 0;
        }
        /*更新最近访问时间和剩余次数以及减少一次使用计数*/
        lr->last = now;
        lr->excess = excess;
        lr->count--;
        /*释放共享内存的锁*/
        ngx_shmtx_unlock(&ctx->shpool->mutex);
        /*上下文中的节点指针置为空*/
        ctx->node = NULL;

        if (limits[n].nodelay) {
        /*location中使用了nodelay标记 跳过*/
            continue;
        }
        /*通过剩余的次数与请求频率计算得到延时的时间*/
        delay = excess * 1000 / ctx->rate;

        if (delay > max_delay) {
        /*
          计算得到的延时值超过了max_delay 
          对max_delay进行更新
        */
            max_delay = delay;
            //更新excess值 外部调用会使用
            *ep = excess;
            //更新location限制数组的位置(在这里是当前的前一个)
            *limit = &limits[n];
        }
    }
    /*
     返回得到的最大延时值
    */
    return max_delay;
}

ngx_http_limit_req_module LRU淘汰算法处理

static void
ngx_http_limit_req_expire(ngx_http_limit_req_ctx_t *ctx, ngx_uint_t n)
{
    ...
    //取得当前的时间    
    now = ngx_current_msec;
    /*
    1. n==1删除一个或者2个请求频率为0的节点
    2. n==0会强制删除一个LRU最老的节点以及一个或者2个请求频率为0的节点
    */
    while (n < 3) {

        if (ngx_queue_empty(&ctx->sh->queue)) { 
           /*LRU队列为空 意味着没有节点 也就无需进行淘汰处理 直接返回*/
            return;
        }
        /*取得最老的LRU节点*/
        q = ngx_queue_last(&ctx->sh->queue);
        /*得到LRU节点对应的红黑树节点 这里使用结构体成员与结构体地址的偏移量计算得到的*/
        lr = ngx_queue_data(q, ngx_http_limit_req_node_t, queue);

        if (lr->count) {
            //统计的请求次数为空 直接返回
            return;
        }

        if (n++ != 0) {
           //n==1时第一次判定就会成立 而n==0时第一次判定不会成立
            /*得到时间差 并取得绝对值*/
            ms = (ngx_msec_int_t) (now - lr->last);
            ms = ngx_abs(ms);

            if (ms < 60000) {
                /*时间差小于60秒 也会直接返回*/
                return;
            }
            /*
            取得还能容忍请求的超出数量
            */
            excess = lr->excess - ctx->rate * ms / 1000;

            if (excess > 0) { //还有剩余 直接返回
                return;
            }
        }
        /*移除LRU队列中的节点*/
        ngx_queue_remove(q);
        /*通过结构体偏移量的计算得到红黑树节点地址*/
        node = (ngx_rbtree_node_t *)
                   ((u_char *) lr - offsetof(ngx_rbtree_node_t, color));
        /*删除红黑树节点*/
        ngx_rbtree_delete(&ctx->sh->rbtree, node);
        /*释放红黑树节点所占用的共享内存*/
        ngx_slab_free_locked(ctx->shpool, node);
    }
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值