開始學習OpenResty

壹頁書發表於2015-11-30
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邏輯

  1. local mysql=require "resty.mysql"
  2. local cjson=require "cjson"
  3. local db,_=mysql:new()
  4. db:set_timeout(1000)
  5. local ok,err,errno,sqlstate=db:connect{
  6.     host="127.0.0.1",
  7.     port=3306,
  8.     database="mvbox",
  9.     user="xx",
  10.     password="xx"
  11. }
  12. if not ok then
  13.     ngx.say("failed to connect:",err,",",errno,",",sqlstate)
  14.     return
  15. end
  16. db:query("drop table if exists t1")
  17. db:query("create table t1(id int primary key auto_increment,name varchar(20))")
  18. db:query("insert into t1(name) values(\'s1\')")
  19. db:query("insert into t1(name) values(\'s2\')")
  20. local res,err,errno,sqlstate=db:query("select * from t1")
  21. if not res then
  22.     ngx.say("bad result:",err,",",errno,",",sqlstate)
  23.     return
  24. end
  25. ngx.say(cjson.encode(res))
  26. 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部落格 ” ,連結:http://blog.itpub.net/29254281/viewspace-1849844/,如需轉載,請註明出處,否則將追究法律責任。

相關文章