原文: lua-resty-limit-traffic/lib/resty/limit/count.md

1. 示例

http {
lua_shared_dict my_limit_count_store 100m; init_by_lua_block {
require "resty.core"
} server {
location / {
access_by_lua_block {
local limit_count = require "resty.limit.count" -- rate: 5000 requests per 3600s
local lim, err = limit_count.new("my_limit_count_store", 5000, 3600)
if not lim then
ngx.log(ngx.ERR, "failed to instantiate a resty.limit.coutn object: ", err)
return ngx.exit(500)
end -- use the Authorization header as the limiting key
local key = ngx.req.get_headers()["Authorization"] or "public"
local delay, err = lim:incoming(key, true) if not delay then
if err == "rejected" then
ngx.header["X-RateLimit-Limit"] = "5000"
ngx.header["X-RateLimit-Remaining"] = 0
return ngx.exit(503)
end
ngx.log(ngx.ERR, "failed to limit count: ", err)
return ngx.exit(500)
end -- the 2nd return value holds the current remaing number
-- of requests for the specified key.
local remaining = err ngx.header["X-RateLimit-Limit"] = "5000"
ngx.header["X-RateLimit-Remaining"] = remaining
}
}
}
}

注: 该模块依赖 lua-resty-core,因此需要:

init_by_lua_block {
require "resty.core"
}

2. 方法

2.1 new

syntax: obj, err = class.new(shdict_name, count, time_window)

实例化 class 的对象,该 class 通过 require "resty.limit.count" 返回。

该 new 方法携带的参数如下:

  • shdict_name: lua_shared_dict 声明的共享内存的名称。建议对不同的限制使用独立的共享内存。
  • count:指定的请求阈值。
  • time_window: 请求个数复位前的窗口时间,以秒为单位。

new 实现如下

local ngx_shared = ngx.shared
local setmetatable = setmetatable
local assert = assert local _M = {
_VERSION = '0.05'
} local mt = {
__index = _M
} -- the "limit" argument controls number of request allowed in a time window.
-- time "window" argument controls the time window in seconds.
function _M.new(dict_name, limit, window)
local dict = ngx_shared[dict_name]
if not dict then
return nil, "shared dict not found"
end assert(limit> 0 and window > 0) local self = {
dict = dict,
limit = limit,
window = window,
} return setmetatable(self, mt)
end

2.2 incoming

syntax: delay, err = obj:incoming(key, commit)

触发新请求传入事件并计算当前请求对指定 key 所需的 delay(如果有的话),或者是否立即拒绝该请求。

该方法接受如下参数:

  • key: 是用户指定限制速率的 key。

    例如,可以使用 host 或 server zone 作为 key,以便限制每个 host 的速率。此外,也可以使用 Authorization 头部值作为 key,以便可以为个人用户限制速率。

    注意该模块没有为该 key 加前缀或后缀来标志该 key,因此用户需要确保该 key 在 lua_shared_dict 共享内存中是唯一的。
  • commit:布尔值。如果设置为 true,则 obj 将会在支持该 obj 的共享内存中记录该事件;否则仅仅是 "dry run"。

该 incoming 方法的放回值依赖如下情况:

  1. 如果请求数没有超过在 new 方法中设置的 count 值,那么该 incoming 返回 0 作为 delay,并将当前时间内余下允许请求的个数作为第二个值返回。
  2. 如果请求数超过了 count 限制,则返回 nil 和错误字符串 "rejected"。
  3. 如果发生错误(如访问共享内存失败),则该方法返回 nil 和错误描述字符串。

incoming 实现如下

function _M.incoming(self, key, commit)
local dict = self.dict
local limit = self.limit
local window = self.window local remaining, ok, err if commit then
remaining, err = dict:incr(key, -1, limit)
if not remaining then
return nil, err
end if remaining == limit - 1 then
ok, err = dict:expire(key, window)
if not ok then
if err == "not found" then
remaining, err = dict:incr(key, -1, limit)
if not remaining then
return nil, err
end ok, err = dict:expire(key, window)
if not ok then
return nil, err
end else
return nil, err
end
end
end else
remaining = (dict:get(key) or limit) - 1
end if remaining < 0 then
return nil, "rejected"
end return 0, remaining
end

OpenResty之 limit.count 模块的更多相关文章

  1. nginx_tcp模块集成到openresty(安装ngx_tcp_lua_module模块)

    git地址:https://github.com/bigplum/nginx-tcp-lua-module openresty 本身是使用http协议进行通讯的, 但是项目中经常有要求输入是使用tcp ...

  2. 又拍云张聪:OpenResty 动态流控的几种姿势

    2019 年 1 月 12 日,由又拍云.OpenResty 中国社区主办的 OpenResty × Open Talk 全国巡回沙龙·深圳站圆满结束,又拍云首席架构师张聪在活动上做了< Ope ...

  3. 从SpringBoot构建十万博文聊聊限流特技

    前言 在开发十万博客系统的的过程中,前面主要分享了爬虫.缓存穿透以及文章阅读量计数等等.爬虫的目的就是解决十万+问题:缓存穿透是为了保护后端数据库查询服务:计数服务解决了接近真实阅读数以及数据库服务的 ...

  4. SpringBoot项目的限流

    开发访问量比较大的系统是,爬虫的目的就是解决访问量大的问题:缓存穿透是为了保护后端数据库查询服务:计数服务解决了接近真实访问量以及数据库服务的压力. 架构图 限流 就拿十万博客来说,如果存在热点文章, ...

  5. 高并发 Nginx+Lua OpenResty系列(4)——Lua 模块开发

    在实际开发中,不可能把所有代码写到一个大而全的lua文件中,需要进行分模块开发:而且模块化是高性能Lua应用的关键.使用require第一次导入模块后,所有Nginx 进程全局共享模块的数据和代码,每 ...

  6. 浏览器给openresty连接发送参数请求,查询数据库,并返回json数据

    nginx.conf配置文件 #user nobody; worker_processes 1; error_log logs/error.log; #error_log logs/error.log ...

  7. OpenResty实现限流的几种方式

      在开发 api 网关的时,做过一些简单的限流,比如说静态拦截和动态拦截:静态拦截说白了就是限流某一个接口在一定时间窗口的请求数.用户可以在系统上给他们的接口配置一个每秒最大调用量,如果超过这个限制 ...

  8. openresty/1.11.2.1性能测试

    测试数据 ab -n -c -k http://127.0.0.1/get_cache_value nginx.conf lua_shared_dict cache_ngx 128m; server ...

  9. 【源码】openresty 限流

    小结: 1.在连接环节计数,有清零环节 有3个参量 maxburst unit_delay https://github.com/openresty/lua-resty-limit-traffic/b ...

随机推荐

  1. Windows Server 2012 R2上安装.Net4.6.1出错

    在Windows Server 2012 R2上安装.Net4.6.1时提示“你需要先安装对应于 KB2919355 的更新,然后才可在……”解决方式: 在官网下载更新包,下载地址:https://w ...

  2. nodejs库express是如何接收inbound json请求的

    这样几行简单的代码创建一个web服务器: var express = require('express'); var app = express(); var server = require('ht ...

  3. 【前端开发】ES6知识点系统化梳理笔记

    >ES6扩展: #Map和Set是es6标准新增的数据类型 ##Map是key-value(关键字-值),Map允许修改value,不允许修改key,Map支持下标操作 var m = new ...

  4. java网络编程--httpurlconnection

    HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现.如果不设置超时(timeout),在网络异常的情况下,可能会导致程序僵死而不继续往下执行.可以通过以下两个语句来 ...

  5. linux命令详解

    命令语法介绍 命令   [参数] [文件或路径] rm       -f                  /etc/hosts 注:命令和参数至少一个空格(可以多个连着写)      路径不带空格  ...

  6. 15 Windows编程——系统内置窗口子类型之button

    button子类型BS_3STATE.BS_AUTO3STATE.BS_AUTOCHECKBOX 源码 #include<Windows.h> #include<Windowsx.h ...

  7. 胡搞-强化版的light oj-1055-的思路-AI版的6重暴力For循环的BFS

    新题目大意: 三个棋子按照先后顺序,可以随意方向合法地走到空位置上(而不是像原题light oj-1055中的一样三个棋子每次走的方向都一致),当三个棋子全部走进目标地点,就结束:求需要指挥的最少次数 ...

  8. Lua 学习之基础篇一<Lua 运算符>

    引言 由于刚接触lua,个人觉得接触一门新语言,就要一定要对基础的部分做一个快速了解. 于是参考网上相关资料吸收并整理下来作为笔记,模糊的时候用来回顾一下. 这些部分基本都是经过自己手动测试梳理过,没 ...

  9. 28-SQLServer带见证服务器的镜像搭建

    一.注意点 1.数据库的模式要是完整模式. 2.要对数据库完整备份和事务日志备份,分别还原到镜像库上,使用NORECOVERY模式. 3.镜像数据库是不允许删除和操作,即便查看属性也不行. 4.先删除 ...

  10. Selenium常用API的使用java语言之8-模拟鼠标操作

    通过前面例子了解到,可以使用click()来模拟鼠标的单击操作,现在的Web产品中提供了更丰富的鼠标交互方式, 例如鼠标右击.双击.悬停.甚至是鼠标拖动等功能.在WebDriver中,将这些关于鼠标操 ...