出于技术储备的目的研究了下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架构师
参考资料