生产环境中 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. 洛谷 P1452 Beauty Contest

    题目背景 此处省略1W字^ ^ 题目描述 贝茜在牛的选美比赛中赢得了冠军”牛世界小姐”.因此,贝西会参观N(2 < = N < = 50000)个农场来传播善意.世界将被表示成一个二维平面 ...

  2. 【动态规划】Gym - 101147H - Commandos

    裸dp,看代码. #include<cstdio> #include<algorithm> #include<cstring> using namespace st ...

  3. python3全栈开发-并发编程,多线程

    一.什么是线程 在传统操作系统中,每个进程有一个地址空间,而且默认就有一个控制线程 线程顾名思义,就是一条流水线工作的过程,一条流水线必须属于一个车间,一个车间的工作过程是一个进程 车间负责把资源整合 ...

  4. Java堆内存不足

    1)使用IDEA开发程序时有时候会提示“Java Heap space error”,说明IDEA默认配置的Java堆内存不足,程序需要更多的堆内存. 2)堆(Heap)和非堆(Non-heap)内存 ...

  5. Mac Screen Capture Shortcuts

    Here's How:   To capture the entire desktop, press Command-Shift-3. The screen shot will be automati ...

  6. Network Connection Lost When Windows 8 Goes To Sleep

    http://www.kapilarya.com/fix-network-connection-lost-when-windows-8-goes-to-sleep http://superuser.c ...

  7. 安网讯通签约孟强美容CRM

    整形美容CRM软件是辽宁安网讯通有限公司为孟强整形医院定制开发的一套客户关系管理软件,软件专门针对整形美容行业专科门诊的需求,能满足大中小整形美容机构或或各种专科科室的日常业务需求. 主要功能包括: ...

  8. Kubernetes连接外部数据源

    Kubernetes架构下比较核心的问题是数据如何persistance,虽然提供了Persistent volumn的方式,但是对于像数据库之类的产品在kubernetes集群环境中运行和管理还是很 ...

  9. python 输出所有大小写字母, range()以及列表切片

    所以在写的时候,只要把它们的ASCII列出,并转化成字符型chr 即可. print [chr(i) for i in range(65,91)]#所有大写字母 print [chr(i) for i ...

  10. XSS跨站脚本测试用例

    '><script>alert(document.cookie)</script>='><script>alert(document.cookie)&l ...