内容简介: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实现流控》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- 使用Akka实现并发
- 使用GOLANG实现猴子排序
- 使用 WebSocket 实现 JsBridge
- 使用 RabbitMQ 实现 RPC
- 使用Kafka实现事件溯源
- 使用 Swift 实现 Promise
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
产品经理全栈运营实战笔记
林俊宇 / 化学工业出版社 / 49.8元
本书凝结作者多年的产品运营经验,读者会看到很多创业公司做运营的经验,书中列举了几十个互联网产品的运营案例去解析如何真正做好一个产品的冷启动到发展期再到平稳期。本书主要分为六篇:互联网运营的全面貌;我的运营生涯;后产品时代的运营之道;揭秘刷屏事件的背后运营;技能学习;深度思考。本书有很多关于产品运营的基础知识,会帮助你做好、做透。而且将理论和作者自己的案例以及其他人的运营案例结合起来,会让读者更容易......一起来看看 《产品经理全栈运营实战笔记》 这本书的介绍吧!