生产环境中 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. 【权值分块】bzoj1861 [Zjoi2006]Book 书架

    权值分块……rank3……没什么好说的. #include<cstdio> #include<cmath> #include<algorithm> using na ...

  2. 【进制转换】CODEVS 1740 进制计算器

    #include<cstdio> #include<iostream> #include<string> using namespace std; string s ...

  3. 重大新闻:腾讯大杀器来了,QQ浏览器微信版推出

    今日,腾讯在推出windows桌面版的微信后,又发布了一个重量级产品:QQ浏览器微信版 我们在PC端用微信又多了一种方式,而且比windows桌面版本更加友好,更加方便. 我相信:对于我们绝大多数办公 ...

  4. winform treeview 绑定文件夹和文件

    转载:http://www.cnblogs.com/zhbsh/archive/2011/05/26/2057733.html #region treeview 绑定文件夹和文件 /// <su ...

  5. Node.js 连接mySQL程序

    环境:Oracle Enterprise Linux R5U7 安装mySQL 关于离线安装,下次在尝试,目前先来在线安装,过程如下: $ rpm -qa | grep -i mysql $ wget ...

  6. mac上虚拟机:VMWare Fusion, VirtualBox, Parallels Desktop, CrossOver, Veertu

    作者:Louis Tong链接:https://www.zhihu.com/question/35731328/answer/66127970来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非 ...

  7. cs-SelectTree-DropTreeNode, SelectTreeList

    ylbtech-Unitity: cs-SelectTree-DropTreeNode, SelectTreeList DropTreeNode.cs SelectTreeList.cs 1.A,效果 ...

  8. http://www.ablanxue.com/shtml/201411/25904_1.shtml

    http://www.ablanxue.com/shtml/201411/25904_1.shtml

  9. Docker解析及轻量级PaaS平台演练(一)--Docker简介与安装

    Container技术: 传统的虚拟化技术: 通过对硬件层模拟,从而实现了能够在一套硬件上面运行多个操作系统,因为通过硬件虚拟化,使得操作系统认为在它之下就是硬件层 但是实际情况是这样的:虚拟机中的O ...

  10. [Functional Programming] Pull Many Random Numbers in a Single State ADT Transaction

    We have the ability to select a single random card from a pile of twelve cards, but we would like to ...