出於技術儲備的目的研究了下openresty,恩,收穫不小,有一種在舊衣服裏找到錢的快感,簡單記錄下本身可能會用到的知識點,作個備忘。html
###安裝 僅限於Mac OSX系統,其餘系統安裝方式自行搜索nginx
//推薦 brew tap homebrew/nginx brew install homebrew/nginx/openresty
orgit
brew install nginx-full --with-lua-module
###學習前準備 nginx.conf打開日誌,方便查看lua腳本或配置自己的錯誤github
access_log /usr/local/var/log/nginx/access.log; error_log /usr/local/var/log/nginx/error.log;
nginx配置和lua腳本變化監聽並重啓nginx的程序,否則每次手動重啓略麻煩,這裏有一個go版本的web
package main import ( "log" "os/exec" "github.com/fsnotify/fsnotify" ) func main() { watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } defer watcher.Close() done := make(chan bool) go func() { for { select { case event := <-watcher.Events: log.Println("event:", event) if event.Op&fsnotify.Write == fsnotify.Write { log.Println("modified file:", event.Name) } nginx() case err := <-watcher.Errors: log.Println("error:", err) } } }() err = watcher.Add("/path/to/file1") if err != nil { log.Fatal(err) } err = watcher.Add("/path/to/file2")//也能夠監聽文件夾 if err != nil { log.Fatal(err) } <-done } func nginx() { cmd := exec.Command("/usr/local/bin/lunchy", "restart", "nginx") //重啓命令根據本身的須要自行調整 cmd.Run() }
###hello,world 在nginx.conf加一段配置api
server { listen 18080; location / { default_type text/html; content_by_lua_block { ngx.say("hello,world") } } }
lua文件版安全
server { listen 18080; location / { default_type text/html; content_by_lua_file /path/to/nginx.lua; } }
nginx.luacookie
ngx.say("hello,world")
###lua開發準備 首先安裝一個庫,使用opm,openresty的包管理工具,其餘的庫用opm搜索。架構
opm install p0pr0ck5/lua-resty-cookie //注意包的安裝路徑,待會要用
修改下server的配置,配置lua的package path。工具
lua_package_path "/usr/local/Cellar/openresty/1.11.2.2_2/site/lualib/resty/?.lua;;"; server { listen 18080; location / { default_type text/html; content_by_lua_file /path/to/nginx.lua; } }
###一兩個web操做
-- COOKIE local ck = require("cookie") local cookie, err = ck:new() local field, err = cookie:get("c") cookie:set({key = "Age", value = "2333333",}) -- GET local arg = ngx.req.get_uri_args() ngx.say(arg.a) for k,v in pairs(arg) do ngx.say("[GET ] key:", k, " v:", v) end
###openresty能幹什麼 在我本身的想法裏,我會用它來作灰度發佈、限流、參數安全校驗、api網關,固然openresty能作的事情不少。
lua頗有意思。
nginx真好玩。
更多架構、PHP、GO相關踩坑實踐技巧請關注個人公衆號:PHP架構師
參考資料