OpenResty下载地址
https://openresty.org/download/ngx_openresty-1.9.3.2.tar.gz
Nginx增加模块需要重新编译.
OpenResty 将很多常用的模块,包括LUA支持,cjson等,直接打包在一起.
使用起来非常的方便.随手用的模块都有,也免去了重新编译的烦恼.
安装:
useradd -m nginx
加压文件,创建目标文件夹OpenResty
[nginx@localhost~]$tar -zxvf ngx_openresty-1.9.3.2.tar.gz
[nginx@localhost~]$mkdir OpenResty
[nginx@localhost~]$cd ngx_openresty-1.9.3.2
然后执行
./configure --prefix=/home/nginx/OpenResty
make -j `cat /proc/cpuinfo | grep processor| wc -l`
make install
安装结束.可以看到Nginx和相关模块已经安装完成.
[nginx@localhost~]$ls OpenResty/
bin luajit lualib nginx
修改Nginx配置文件,通过Lua访问MySQL
vim /home/nginx/OpenResty/nginx/conf/nginx.conf

创建/home/nginx/lua_mysql.lua文件,增加lua逻辑
-
local mysql=require "resty.mysql"
-
local cjson=require "cjson"
-
local db,_=mysql:new()
-
db:set_timeout(1000)
-
local ok,err,errno,sqlstate=db:connect{
-
host="127.0.0.1",
-
port=3306,
-
database="mvbox",
-
user="xx",
-
password="xx"
-
}
-
if not ok then
-
ngx.say("failed to connect:",err,",",errno,",",sqlstate)
-
return
-
end
-
db:query("drop table if exists t1")
-
db:query("create table t1(id int primary key auto_increment,name varchar(20))")
-
db:query("insert into t1(name) values(\'s1\')")
-
db:query("insert into t1(name) values(\'s2\')")
-
local res,err,errno,sqlstate=db:query("select * from t1")
-
if not res then
-
ngx.say("bad result:",err,",",errno,",",sqlstate)
-
return
-
end
-
ngx.say(cjson.encode(res))
-
db:close()
测试结果:
[nginx@localhost~]$curl http://172.16.1.78:8088/lua_mysql
[{"name":"s1","id":1},{"name":"s2","id":2}]
他这个db:query是冒号..
下面这种用法,比较有意思.

参考:
https://github.com/openresty/lua-resty-mysql
http://openresty.org/cn/
http://blog.csdn.net/qinyushuang/article/details/43950497
http://www.tuicool.com/articles/iayuqi
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-1849844/
,如需转载,请注明出处,否则将追究法律责任。