Nginx——openresty配置与实战
摘要
Lua 是一种轻量小巧的脚本语言,用标准C语言编写并以源代码形式开放, 其设计目的是为了嵌入应用程序中,从而为应用程序提供灵活的扩展和定制功能。Lua 是巴西里约热内卢天主教大学(Pontifical Catholic University of Rio de Janeiro)里的一个研究小组于 1993 年开发的,该小组成员有:Roberto Ierusalimschy、Waldemar Celes 和 Luiz Henrique de Figueiredo。
一、lua、luajit、openresty
1.1 Lua 特性
- 轻量级: 它用标准C语言编写并以源代码形式开放,编译后仅仅一百余K,可以很方便的嵌入别的程序里。
- 可扩展: Lua提供了非常易于使用的扩展接口和机制:由宿主语言(通常是C或C++)提供这些功能,Lua可以使用它们,就像是本来就内置的功能一样。
- 其它特性:
- 支持面向过程(procedure-oriented)编程和函数式编程(functional programming);
- 自动内存管理;只提供了一种通用类型的表(table),用它可以实现数组,哈希表,集合,对象;
- 语言内置模式匹配;闭包(closure);函数也可以看做一个值;提供多线程(协同进程,并非操作系统所支持的线程)支持;
- 通过闭包和table可以很方便地支持面向对象编程所需要的一些关键机制,比如数据抽象,虚函数,继承和重载等。
Lua 应用场景
- 游戏开发
- 独立应用脚本
- Web 应用脚本
- 扩展和数据库插件如:MySQL Proxy 和 MySQL WorkBench
- 安全系统,如入侵检测系统
1.2 LuaJIT(Lua解释器)
LuaJIT的运行环境包括一个用手写汇编实现的Lua解释器和一个可以直接生成机器代码的JIT编译器。Lua代码在被执行之前总是会先被lfn
生成LuaJIT自己定义的字节码ByteCode
。
开始时Lua字节码总是被LuaJIT的解释器解释执行,LuaJIT的解释器会在执行字节码时同时记录一些运行时的统计信息,如每个Lua函数调用入口的实际运行次数,还有每个Lua循环的实际执行次数。当这些次数超过某个预设的阈值时,便认为对应的Lua函数入口或对应的Lua循环足够的热,此时便会触发JIT编译器开始工作。
JIT编译器会从热函数的入口或热循环的某个位置开始尝试编译对应的Lua代码路径,编译的过程是把LuaJIT字节码先转换成LuaJIT自己定义的中间码(IR),然后再生成针对目标体系结构的机器码,如x86_64指令组成的机器码。如果当前Lua代码路径上的所有操作都可以被JIT编译器顺利编译,则这条编译过的代码路径便被称为一个trace
,在物理上对应一个trace
类型的GC对象,即参与Lua GC的对象。
1.3 OpenResty
OpenResty® 是一个基于Nginx与Lua 的高性能 Web平台,其内部集成了大量精良的 Lua 库、第三方模块以及大多数的依赖项。用于方便地搭建能够处理超高并发、扩展性极高的动态 Web 应用、Web 服务和动态网关。
OpenResty® 通过汇聚各种设计精良的Nginx模块(主要由 OpenResty 团队自主开发),从而将 Nginx有效地变成一个强大的通用 Web 应用平台。这样,Web 开发人员和系统工程师可以使用 Lua 脚本语言调动 Nginx支持的各种 C 以及 Lua 模块,快速构造出足以胜任 10K 乃至 1000K 以上单机并发连接的高性能 Web 应用系统。
OpenResty® 的目标是让你的Web服务直接跑在Nginx服务内部,充分利用 Nginx 的非阻塞 I/O 模型,不仅仅对 HTTP 客户端请求,甚至于对远程后端诸如 MySQL、PostgreSQL、Memcached 以及 Redis 等都进行一致的高性能响应。
下面是在我的ThinkPad T400笔记本电脑上使用ab -c10 -n50000 http://localhost:8080/ 命令的结果,ngx_openresty 0.8.54.6:----------------------------------------------------------------------Server Software: ngx_openresty/0.8.54
Server Hostname: localhost
Server Port: 8080Document Path: /
Document Length: 20 bytesConcurrency Level: 10
Time taken for tests: 2.459 seconds
Complete requests: 50000
Failed requests: 0
Write errors: 0
Total transferred: 8550342 bytes
HTML transferred: 1000040 bytes
Requests per second: 20335.69 [#/sec] (mean)
Time per request: 0.492 [ms] (mean)
Time per request: 0.049 [ms] (mean, across all concurrent requests)
Transfer rate: 3396.04 [Kbytes/sec] receivedConnection Times (ms)min mean[+/-sd] median max
Connect: 0 0 0.1 0 8
Processing: 0 0 0.2 0 8
Waiting: 0 0 0.1 0 8
Total: 0 0 0.2 0 8Percentage of the requests served within a certain time (ms)50% 066% 075% 080% 090% 195% 198% 199% 1100% 8 (longest request)
二、openresty连接mysql
2.1 centos 安装mysql服 server
# Centos系统下安装mysqlcd /usr/downloads/wget http://dev.mysql.com/get/mysql-community-release-el7-5.noarch.rpmrpm -ivh mysql-community-release-el7-5.noarch.rpmyum install mysql-community-server# 安装成功后,重启mysql,并进入mysql数据库,给root用户设置一个密码,密码为“123”。service mysqld restartmysql -u root -pset password for root@localhost = password('123');
2.2 openresty连接mysql server
lua-resty-mysql模块是基于cosocket API 为ngx_lua提供的一个Lua MySQL客户端。它保证了100%非阻塞。vim /usr/example/lua/test_mysql.lua,添加以下的代码:
local function close_db(db) if not db then return end db:close()
end local mysql = require("resty.mysql") local db, err = mysql:new()
if not db then ngx.say("new mysql error : ", err) return
end db:set_timeout(1000) local props = { host = "127.0.0.1", port = 3306, database = "mysql", user = "root", password = "123"
} local res, err, errno, sqlstate = db:connect(props) if not res then ngx.say("connect to mysql error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate) return close_db(db)
end local drop_table_sql = "drop table if exists test"
res, err, errno, sqlstate = db:query(drop_table_sql)
if not res then ngx.say("drop table error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate) return close_db(db)
end local create_table_sql = "create table test(id int primary key auto_increment, ch varchar(100))"
res, err, errno, sqlstate = db:query(create_table_sql)
if not res then ngx.say("create table error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate) return close_db(db)
end local insert_sql = "insert into test (ch) values('hello')"
res, err, errno, sqlstate = db:query(insert_sql)
if not res then ngx.say("insert error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate) return close_db(db)
end res, err, errno, sqlstate = db:query(insert_sql) ngx.say("insert rows : ", res.affected_rows, " , id : ", res.insert_id, "<br/>") local update_sql = "update test set ch = 'hello2' where id =" .. res.insert_id
res, err, errno, sqlstate = db:query(update_sql)
if not res then ngx.say("update error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate) return close_db(db)
end ngx.say("update rows : ", res.affected_rows, "<br/>") local select_sql = "select id, ch from test"
res, err, errno, sqlstate = db:query(select_sql)
if not res then ngx.say("select error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate) return close_db(db)
end for i, row in ipairs(res) do for name, value in pairs(row) do ngx.say("select row ", i, " : ", name, " = ", value, "<br/>") end
end ngx.say("<br/>") local ch_param = ngx.req.get_uri_args()["ch"] or '' local query_sql = "select id, ch from test where ch = " .. ngx.quote_sql_str(ch_param)
res, err, errno, sqlstate = db:query(query_sql)
if not res then ngx.say("select error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate) return close_db(db)
end for i, row in ipairs(res) do for name, value in pairs(row) do ngx.say("select row ", i, " : ", name, " = ", value, "<br/>") end
end local delete_sql = "delete from test"
res, err, errno, sqlstate = db:query(delete_sql)
if not res then ngx.say("delete error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate) return close_db(db)
end ngx.say("delete rows : ", res.affected_rows, "<br/>") close_db(db)
vim /usr/example/example.conf 在配置文件配置:
location /lua_mysql {default_type 'text/html';lua_code_cache on;content_by_lua_file /usr/example/lua/test_mysql.lua;}
浏览器访问http://ip/lua_mysql,浏览器显示以下的内容:
insert rows : 1 , id : 2
update rows : 1
select row 1 : ch = hello
select row 1 : id = 1
select row 2 : ch = hello2
select row 2 : id = 2delete rows : 2
三、openresty连接redis
连接redis集群需要用到 lua-resty-redis-cluster模块, 下载完成之后,只需要用到包中的2个文件rediscluster.lua和redis_slot.c 复制包中的 redis_slot.c 到openresty安装目录的lualib下,rediscluster.lua到lualib下的resty下 .c文件无法在Nginx配置文件中引入,需要编译成.so文件,编译命令。
3.1 centos 安装redis server
# 安装gcc、c++编译器以及内核文件yum -y install gcc gcc-c++ kernel-devel# centos自带lua需要执行此命令再编译,自己安装过lua不需要yum install lua-devel#编译命令gcc redis_slot.c -fPIC -shared -o libredis_slot.so#查看结果ll
nginx.conf配置文件中http下添加
#lua模块路径,多个之间”;”分隔,其中”;;”表示默认搜索路径,默认到/usr/servers/nginx下找 lua_package_path "/opt/openresty/lualib/?.lua;;/opt/openresty/nginx/conf/openResty/?.lua;;"; #lua 模块lua_package_cpath "/opt/openresty/lualib/?.so;";include /opt/openresty/nginx/conf/openResty/openResty.conf;
#user nobody;
worker_processes 1;#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;#pid logs/nginx.pid;events {worker_connections 1024;
}http {include mime.types;default_type application/octet-stream;#日志格式log_format my_format '$remote_addr^A$msec^A$http_host^A$request_uri';#access_log logs/access.log main;sendfile on;#tcp_nopush on;#keepalive_timeout 0;keepalive_timeout 65;upstream lua.redis.com{server 192.168.164.25:8090;}#gzip on;#lua模块路径,多个之间”;”分隔,其中”;;”表示默认搜索路径,默认到/usr/servers/nginx下找 lua_package_path "/opt/openresty/lualib/?.lua;;/opt/openresty/nginx/conf/openResty/?.lua;;"; #lua 模块lua_package_cpath "/opt/openresty/lualib/?.so;";include /opt/openresty/nginx/conf/openResty/openResty.conf;
}
/opt/openresty/nginx/conf/openResty目录下新增openResty.conf
server {listen 80;server_name lua.redis.com;#单机版redislocation /lua_redis_single {default_type 'text/html';charset utf-8;lua_code_cache off;content_by_lua_file conf/openResty/lua/redis/redis-util.lua;} #集群版redislocation /lua_redis {default_type 'text/html';charset utf-8;lua_code_cache off;content_by_lua_file conf/openResty/lua/redis/redis-cluster.lua;}#redis中k为空则将请求转发到当前后台服务器进行查询location /redis {default_type 'text/plain';proxy_pass http://lua.redis.com;}
}
3.2 openresty连接redis server
连接单机版REDIS,redis-util.lua
local function close_redes( red )if not red thenreturnend-- 释放连接(连接池实现)local pool_max_idle_time = 10000 -- 毫秒local pool_size = 100 --连接池大小local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)if not ok thenngx.say("set keepalive error : ", err)end
endlocal redis = require("resty.redis")-- 创建实例
local red = redis:new()
-- 设置超时(毫秒)
red:set_timeout(2000)
-- 建立连接
local ip = "192.168.2.110"
local port = 6379
local ok, err = red:connect(ip, port)
if not ok thenreturn
end
local res, err = red:auth("jinku_redis")
if not res thenngx.say("connect to redis error : ", err)return
end-- 选择db 3
ok, err = red:select(3)
if not ok thenngx.say("failed to select db: ", err)return
endred:init_pipeline()
red:set("msg1", "hello1")
red:set("msg2", "hello2")
red:get("msg1")
red:get("msg2")
local respTable, err = red:commit_pipeline()-- 得到数据为空处理
if respTable == ngx.null thenrespTable = {}
end-- 结果是按照执行顺序返回的一个table
for i, v in ipairs(respTable) dongx.say("msg : ", v, "<br/>")
endclose_redes(red)
/opt/openresty/nginx/conf/openResty/lua/redis目录下新增redis-cluster.lua
local config = {name = "test",serv_list = {{ip="192.168.164.24", port = 7000},{ip="192.168.164.24", port = 7001},{ip="192.168.164.24", port = 7002},{ip="192.168.164.24", port = 7003},{ip="192.168.164.24", port = 7004},{ip="192.168.164.24", port = 7005},}
}-- 获取连接
local redis_cluster = require "resty.rediscluster"
local red = redis_cluster:new(config)--Nginx服务器中使用lua获取get或post参数
local request_method = ngx.var.request_method
local args = nil
local param = nil--获取url参数的值
if "GET" == request_method thenargs = ngx.req.get_uri_args()
elseif "POST" == request_method thenngx.req.read_body()args = ngx.req.get_post_args()
end
param = args["k"]-- 使用pipeline操作业务
-- red:init_pipeline()
local result=red:get(param)
-- local results = red:commit_pipeline()
local cjson = require "cjson"if result == ngx.null then-- 转发到后台tomcat服务器去查询并且缓存local resp = ngx.location.capture("/redis/getV?k="..param)result = resp.body
endngx.say(cjson.encode(result))red:close()
访问 http://lua.redis.com/lua_redis?k=myName请求lua_redis, http://lua.redis.com/redis/getV?k=myName 跳过lua_redis,直接访问redis springboot工程
博文参考
优化超大 Nginx 配置导致的内存碎片 - OpenResty 官方博客
lua-resty-template: 适用于Lua和OpenResty的模板引擎(HTML)。
GitHub - openresty/lua-resty-redis: Lua redis client driver for the ngx_lua based on the cosocket API
GitHub - openresty/lua-resty-mysql: Nonblocking Lua MySQL driver library for ngx_lua or OpenResty
LuaJIT - 简书
The LuaJIT Project
Lua 教程 | 菜鸟教程
OpenResty - 下载