生产环境中 Ngx_lua 使用技巧和应用的范例

时间 -- ::  51CTO技术博客
原文 http://rfyiamcool.blog.51cto.com/1030776/1252501
主题 Lua
Lua的性能超牛的,这个不需要再啰嗦了。。。 Nginx_lua的适用场景 网络I/O 阻塞时间远高于CPU 计算占用时间、同时上游资源非瓶颈(可伸缩)的网络应用,如高性能网络中间层、HTTP REST 接口服务等; 期望简化系统架构,让服务向Nginx 同质化的Web 站点; 淘宝人对于ngx_lua使用的总结: 优势: 同步非阻塞I/O 形式直观易懂,并发服务能力强 CPU、内存运行开销低 同Nginx 结合度高,可方便粘合现有Nginx 模块功能 劣势: 属于新技术方案,Lua 相比于PHP、Ruby 等广泛使用的开发 语言,周边附属设施尚不够健全,需要时间积累 安装就简单过一遍,其实大家用openresty就行啦。。。 作者已经做了很多的调优。。。 还是推荐大家用 openresty。。。 最少在测试环境下用这个,可以省去很多找模块,折腾模块的时间。。。 .下载nginx
wget http://nginx.org/download/nginx-1.2.2.tar.gz
.安装gcc
sudo apt-get install gcc
.下载LuaJIT
wget http://luajit.org/download/LuaJIT-2.0.0-beta10.tar.gz
. 安装LuaJIT
tar -xzvf LuaJIT-2.0.-beta10.tar.gz
cd LuaJIT-2.0.-beta10
make && sudo make install
.下载 ngx_devel_kit(在这个页面找:https://github.com/simpl/ngx_devel_kit/tags)
wget https://github.com/simpl/ngx_devel_kit/tarball/master -O simpl-ngx_devel_kit.tar.gz
.下载最新的 lua-nginx-module(在这个页面找:https://github.com/chaoslawful/lua-nginx-module/tags)
wget https://github.com/chaoslawful/lua-nginx-module/tarball/master -O lua-nginx-module.tar.gz
.下载pcre
wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.31.tar.gz
tar -xzvf pcre-8.31.tar.gz ./configure && make(如果报“compile: unrecognized option `-DHAVE_CONFIG_H'”,请安装sudo apt-get install build-essential)
sudo make install
.下载echo模块
wget https://github.com/agentzh/echo-nginx-module/tarball/master -O echo-nginx-module.tar.gz
tar -xzvf echo-nginx-module.tar.gz . 解压nginx,ngx_devel_kit, lua-nginx-module
tar -xzvf nginx-1.2..tar.gz
tar -xzvf simpl-ngx_devel_kit.tar.gz
tar -xzvf lua-nginx-module.tar.gz
.安装
sudo apt-get install openssl libssl-dev
sudo apt-get install libtool
cd nginx-1.2.
export LUAJIT_LIB=/usr/local/lib/
export LUAJIT_INC=/usr/local/include/luajit-2.0 ./configure --user=www-data --group=www-data --with-debug --with-http_gzip_static_module --with-http_ssl_module --with-http_stub_status_module --with-http_realip_module \
--prefix=/usr/local/nginx \
--add-module=../simpl-ngx_devel_kit-4192ba6/ \
--add-module=../chaoslawful-lua-nginx-module-b771a2e/\
--add-module=../agentzh-echo-nginx-module-8042c62/ make -j2
sudo make install
一定要注意他的执行顺序 : Rewrite phase. Access phase. Content phase. 详细的步骤: .init_by_lua 上下文http ngx启动时执行
. set_by_lua 上下文 server, server if, location, location if
.rewrite_by_lua 上下文 http, server, location, location if
.access_by_lua 上下文 http, server, location, location if
.content_by_lua 上下文 location, location if
.header_filter_by_lua 上下文 http, server, location, location if
.body_filter_by_lua 上下文 http, server, location, location if
.log_by_lua 上下文 http, server, location, location if
咱们再过滤post、get请求或者是触发了某个access、rewrite,如果发现恶意和违规的侵入的话,可以发邮件报警,好让我们第一时间收到邮件的信息。。。 location = /smtp {
default_type "text/plain";
content_by_lua '
local smtp = require("socket.smtp")
local from = "<ruifengyunceshi@163.com>"
local rcpt = {"",}
local mesgt = {
headers = {
to = "", -- 收件人
subject = "This is Mail Title"
},
body = "This is Mail Content."
}
local r, e = smtp.send{
server="smtp.163.com",
user="",
password="",
from = from,
rcpt = rcpt,
source = smtp.message(mesgt)
}
if not r then
ngx.say(e)
else
ngx.say("send ok!")
end
';
}
lua这东西挺怪的,他的双引号和单引号是有很大区别的,我到现在也没搞明白,啥区别,反正用双引号就对了。。。有事error.log报错的话,改成单引号试试。。 好点的方法是 先在lua的环境中跑一边,ok后,在放到ngx_lua里面。 Lua有丰富的接口的方案,不只是给别人提供的接口,还有他自己访问别的接口所用的模块。 如果你的同事那边已经有个高性能的socket接口,那你就别麻烦他改成rest模式了。。。 毕竟socket对socket速度很快的。 location /cosocket {
default_type "text/plain";
content_by_lua '
local sock = ngx.socket.tcp()
sock:settimeout()
local ok, err = sock:connect("127.0.0.1", )
if not ok then
ngx.say("failed to connect: ", err)
return
end
local bytes, err = sock:send("flush_all")
ngx.say(bytes,err)
if not bytes then
ngx.say("failed to send query: ", err)
return
end
local line, err = sock:receive()
if not line then
ngx.say("failed to receive a line: ", err)
return
end
ngx.say("result: ", line)
';
} }
} 对于给别人的mysql查询,给账号密码不合适,和一个小权限的账号密码也不合适。 这种情况,我们要是求高性能的话,可以用lua配置cjson做成rest接口。 location /select2 {
content_by_lua '
local mysql = require "resty.mysql"
local db,err = mysql:new()
if not db then
ngx.say("failed to instantiate mysql: ",err)
return
end
db:set_timeout()
local ok,err,errno,sqlstate = db:connect{
host = "127.0.0.1",
port = ,
database = "niubi",
user = "ruifengyun",
password = "",
max_package_size =
}
if not ok then
ngx.say("failed to connect: ", err, ": ", errno, " ", sqlstate)
return
end
ngx.say("connected to mysql.")
res,err,errno,sqlstate = db:query("select username,password from users where id="..ngx.var.arg_id)
if not res then
ngx.say("bad result: ", err, ": ", errno, ": ", sqlstate, ".")
return
end
local cjson = require "cjson"
ngx.say("result: “,cjson.encode(res))
';
} 咱们既然知道了 lua的强大之处, 可以从lua里面搞负载均衡。 往redis里面 扔两个key 比如 web1 8.8.8.111 web2 8.8.8.222 server {
listen ;
server_name _;
server_name_in_redirect off;
port_in_redirect off;
root /root/html;
location / {
set $upstream "";
rewrite_by_lua '
local routes = _G.routes
-- setup routes cache if empty
if routes == nil then
routes = {}
ngx.log(ngx.ALERT, "Route cache is empty.")
end
-- try cached route first local route = routes[ngx.var.http_host]
if route == nil then
local redis = require "redis"
local client = redis.connect("localhost", )
route = client:get(ngx.var.http_host)
end
if route ~= nil then
ngx.var.upstream = route
routes[ngx.var.http_host] = route
_G.routes = routes
else
ngx.exit(ngx.HTTP_NOT_FOUND)
end
';
proxy_buffering off;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_redirect off;
proxy_connect_timeout ;
proxy_send_timeout ;
proxy_read_timeout ;
proxy_pass http://$upstream;
}
}
用lua 对cookie的控制 header_filter_by_lua '
t = {}
if ngx.var.http_cookie then
s = ngx.var.http_cookie
for k, v in string.gmatch(s, "(%w+)=([%w%/%.=_-]+)") do
t[k] = v
end
end p = ngx.req.get_uri_args() if not t.uid and p.uid then
expires = ngx.cookie_time()
ngx.header["Set-Cookie"] = {"uid=" .. p.uid .."; expires=" .. expires .. ";
end ';

生产环境中 Ngx_lua 使用技巧和应用的范例的更多相关文章

  1. 在生产环境中安全执行更新删除SQL脚本的技巧

    今天在生产环境上解决问题,由于广发银行的管理制度是开发公司是不允许确生产环境的,所以我们只能把要更新的语句发给运营中心,由运营中心的投产人员执行,我们则在旁边看着:在他执行的时候发现了一个很有趣的技巧 ...

  2. Dubbo Mesh 在闲鱼生产环境中的落地实践

    本文作者至简曾在 2018 QCon 上海站以<Service Mesh 的本质.价值和应用探索>为题做了一次分享,其中谈到了 Dubbo Mesh 的整体发展思路是“借力开源.反哺开源” ...

  3. Flink 实战:如何解决生产环境中的技术难题?

    大数据作为未来技术的基石已成为国家基础性战略资源,挖掘数据无穷潜力,将算力推至极致是整个社会面临的挑战与难题. Apache Flink 作为业界公认为最好的流计算引擎,不仅仅局限于做流处理,而是一套 ...

  4. .NET跨平台之旅:在生产环境中上线第一个运行于Linux上的ASP.NET Core站点

    2016年7月10日,我们在生产环境中上线了第一个运行于Linux上的ASP.NET Core站点,这是一个简单的提供后端服务的ASP.NET Core Web API站点. 项目是在Windows上 ...

  5. 理解Docker(6):若干企业生产环境中的容器网络方案

    本系列文章将介绍 Docker的相关知识: (1)Docker 安装及基本用法 (2)Docker 镜像 (3)Docker 容器的隔离性 - 使用 Linux namespace 隔离容器的运行环境 ...

  6. .NET跨平台之旅:生产环境中第2个跑在Linux上的ASP.NET Core站点

    今天我们在生产环境中上线了第2个跑在Linux上的ASP.NET Core站点.这是一个简单的Web API站点,通过命令行的方式调用安装在Linux服务器上的程序完成操作.之前用的是nodejs,现 ...

  7. 【原】Storm Local模式和生产环境中Topology运行配置

    Storm入门教程 1. Storm基础 Storm Storm主要特点 Storm基本概念 Storm调度器 Storm配置 Guaranteeing Message Processing(消息处理 ...

  8. 生产环境中CentOS7部署NET Core应用程序

    NET Core应用程序部署至生产环境中(CentOS7) 阅读目录 环境说明 准备你的ASP.NET Core应用程序 安装CentOS7 安装.NET Core SDK for CentOS7. ...

  9. 生产环境中使用Docker Swarm的一些建议

    译者按: 实践中会发现,生产环境中使用单个Docker节点是远远不够的,搭建Docker集群势在必行.然而,面对Kubernetes, Mesos以及Swarm等众多容器集群系统,我们该如何选择呢?它 ...

随机推荐

  1. 【数位dp】hdu3555 Bomb

    题意就是找0到n有多少个数中含有49.数据范围接近10^20 DP的状态是2维的dp[len][3]dp[len][0] 代表长度为len不含49的方案数dp[len][1] 代表长度为len不含49 ...

  2. BUG YII2.0 cURL error 6: Could not resolve host:

    BUG描述:登录直接显示 原因:服务器设置端口权限,或者DNS毛病 解决方案:只能去服务器端设置,配置端口 DNS: 修改dns 114.114.114.114 或者 8.8.8.8

  3. jquery区分苹果浏览器和安卓浏览器

    var browser={ versions:function(){ var u = navigator.userAgent, app = navigator.appVersion; return { ...

  4. iOS应用程序多语言本地化

    多语言在应用程序中一般有两种做法:一.程序中提供给用户自己选择的机会:二.根据当前用户当前移动设备的语言自动将我们的app切换对应语言. 第一种做法比较简单完全靠自己的发挥了,这里主要讲第二种做法,主 ...

  5. Ubuntu 16.04下Shell脚本中使用数组提示:Syntax error: "(" unexpected

    说明:这种现象在CentOS中不会出现. 分析: 可以看出sh指向了dash 解决方式: 1.不要用sh执行,使用./test.sh执行.或者bash执行. 2.根治,直接修改sh的指向,改成bash ...

  6. 快速开发框架(FDMS)新增1000个对外接口都不须要手写一行代码

    一个大型系统难免会跟其它系统有数据交换,这里就要提供数据接口给外部系统. 曾经在一家智能终端设备的公司上班.那段时间的主要工作就是写接口.接口须要与手机.手持设备.系统管理软件等进行数据交换.总结了一 ...

  7. Android studio百度地图demo出现230错误,key校验失败

    转自daoxiaomianzi原文 Android studio 百度地图demo出现230错误,key校验失败 使用AndroidStudio导入Baidu地图的as版的demo,引入后,发现没有k ...

  8. 【开源类库学习】MBProgressHUD(提示框)

    新博客: http://www.liuchendi.com MBProgressHUD是一个开源类库,实现了各种样式的提示框, 下载地址:https://github.com/jdg/MBProgre ...

  9. DBA_SEGMENTS - 查看数据库对象所分配的物理存储空间

    SELECT SEGMENT_NAME,SEGMENT_TYPE,<code>TABLESPACE_NAME</code>,EXTENTS,BLOCKS,BYTES/1024/ ...

  10. linux基础-第十八单元_nginx部署

    一.基本环境配置 1.1.安装常用软件 yum install wget -y 1.2.Install yum repo mv /etc/yum.repos.d/CentOS-Base.repo /e ...