openresty 它打包了標準的 nginx 核心,很多的常用的第三方模塊,以及它們的大多數依賴項。
如果需要nginx的第三方庫的時候,可以考慮OpenResty,可以少掉很多安裝的麻煩,OpenResty基本上安裝了常用的nginx第三方庫。
OpenResty的安裝:
安裝nginx 中 rewrite模塊等需要的插件:
apt-get install libreadline-dev libpcre3-dev libssl-dev perl build-essential
場景:對返回值有要求的、接口屏蔽字段、或做一些業務上的驗證等
1、windows直接下載openresty 解壓即可,就完成了windows下使用lua的開發環境
2、配置:
a、在nginx.conf里http下配置如下代碼:
include mime.types; default_type application/octet-stream; lua_package_path "/lualib/?.lua;;"; #lua 模塊 lua_package_cpath "/lualib/?.so;;"; #c模塊 include lua.conf; #導入自定義lua配置文件 resolver 8.8.8.8;
b、在nginx.conf同目錄創建lua.conf文件專門存放lua的路由配置
#lua.conf?? server?{?? charset?utf-8;?#設置編碼 ????listen???????80;?? ????server_name??_;?? location?/user?{?? default_type?'text/html';?? content_by_lua_file?lua/api/userController.lua;?#相對于nginx安裝目錄?? }? }??
c、在ngx根目錄下的lua文件夾里創建“api”文件夾,并且在里面添加userController.lua 處理文件類,例如代碼如下:
local?request_method?=?ngx.var.request_method local?args?=?nil --1、獲取參數的值?獲取前端提交參數 if?"GET"?==?request_method?then ????args?=?ngx.req.get_uri_args() elseif?"POST"?==?request_method?then ????ngx.req.read_body() ????args?=?ngx.req.get_post_args() end --2、組合url請求Get/Post請求?并獲取參數?? local?http?=?require?"resty.http"?? local?httpc?=?http.new()?? local?url?=?"http://xxxxx/user/login/"..args["userid"].."/"..args["pass"] local?resStr?--響應結果?? local?res,?err?=?httpc:request_uri(url,?{?? ????method?=?"GET",?? ????--args?=?str,?? ?????body?=?"a=1&b=2", ????headers?=?{?? ???????["Content-Type"]?=?"application/json",?? ????}?? })?? --3、開始重新組合參數?例子?可根據返回的JSON自己處理 local?cjson?=?require?"cjson" local?sampleJson?=?[[{"age":"23","testArray":{"array":[8,9,11,14,25]},"Himi":"himigame.com"}]]; --解析json字符串 local?data?=?cjson.decode(sampleJson); --打印json字符串中的age字段 ngx.say(data["age"]); --打印數組中的第一個值(lua默認是從0開始計數) ngx.say(data["testArray"]["array"][1]);?? --4、打印輸出新返回值 ngx.say(res.body)
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END