使用OpenResty实现流控

栏目: 服务器 · Nginx · 发布时间: 5年前

内容简介:OpenResty是一种基于Nginx并且使用C语言开发的、同时使用Lua作为用户语言的Web平台。如果把Nginx比作Linux内核,那么OpenResty则可以看做是一种Liunx的发行版,其对原有的Nginx做了很大的补充与扩展,使得我们可以在Nginx中编写并执行Lua脚本。创建openresty用户安装openresty(其它环境的

OpenResty是一种基于Nginx并且使用 C语言 开发的、同时使用 Lua 作为用户语言的Web平台。如果把Nginx比作 Linux 内核,那么OpenResty则可以看做是一种Liunx的发行版,其对原有的Nginx做了很大的补充与扩展,使得我们可以在Nginx中编写并执行Lua脚本。

OpenResty环境搭建

创建openresty用户

useradd openresty

安装openresty(其它环境的 安装方法 )

sudo yum-config-manager --add-repo https://openresty.org/yum/cn/centos/OpenResty.repo
sudo yum install openresty

创建文件夹openresty-test,并根据以下的目录结构创建文件夹以及相应的文件

$ tree openresty-test/
openresty-test/
├── conf
│   └── nginx.conf
├── logs
│   ├── access.log
│   └── error.log
└── lua
    └── nginx.lua

openresty-test文件夹应属于openresty用户,如果不是使用如下命令进行修改

chown -R openresty:openresty openresty-test

修改nginx.conf如下

worker_processes 1;
error_log logs/error.log;
events {
    worker_connections 1024;
}

http {
    server {
        listen 6699;
        location / {
            default_type text/html;
            # 关闭lua缓存,只能用于方便调试,修改lua文件后nginx不需要重新reload
            lua_code_cache off;
            # 引入Lua脚本文件
            content_by_lua_file lua/nginx.lua;
        }
    }
}

以上内容设置完毕之后,启动openresty

openresty -p openresty-test

如果需要重新加载配置文件

openresty -p openresty-test -s reload

编写限流脚本

在nginx.conf中我们把 lua/nginx.lua 引入到了配置中,接下来我们开始书写Lua代码。

我们的限流使用了 Redis 来帮助实现,具体代码如下

-- 修改content-type
ngx.header.content_type = "text/plain"

local ip = ngx.req.get_headers()["X-Real-IP"]
if ip == nil then
    ip = ngx.req.get_headers()["x_forwarded_for"]
end
if ip == nil then
    ip = ngx.var.remote_addr
end

local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 一秒

local ok, err = red:connect("172.19.3.27", 6379)
if not ok then
    ngx.say("failed to connect: ", err)
    return
end

local freq = "freq." .. ip -- 出现频率
local bucket = "bucket." .. ip

local res, err = red:get(bucket)
if res == ngx.null then
    red:set(freq, 0) -- 重置频率
    red:set(bucket, 0)
    red:expire(bucket, 10)
end

local num = tonumber(red:get(freq))
if num ~= nil and num > 5 then
    ngx.say("访问频率受限")
    return
end

ngx.say(num)
red:incr(freq)

以上所述就是小编给大家介绍的《使用OpenResty实现流控》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

成功由我

成功由我

刘世英、彭征 / 湖南人民出版社 / 2010-2 / 28.00元

《成功由我:李彦宏快乐成功之道》讲述:他,18岁高分考入北京大学,毕业后到美国名校学习最热门的计算机专业,然后闯荡于华尔街和硅谷这两大金融和技术圣地,31岁回国创立百度……到如今身价数十亿美元,领导的百度发展成为全球第二大搜索引擎,在国内搜索市场占据近八成的市场份额,将有“上帝”之称的Google抛在身后,最近他又掀起了“框计算”风暴,并雄心万丈宣称“未来十年,要让百度在全球一半以上国家成为家喻户......一起来看看 《成功由我》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

SHA 加密
SHA 加密

SHA 加密工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器