OpenResty 之安裝測試

  • 2019 年 11 月 28 日
  • 筆記

OpenResty 之前一直比較關注,後來在工作中也有幸簡單的使用過,穩定性和易用性給了我深刻的印象。

有時回想起曾經接觸過很多有趣的項目和技術,但大部分都浮於表面,很多都是給自己找借口, 想之後有時間再深入研究分享下,卻由於自己的懶惰大部分都不了了之。

要不再給我一次機會, 讓我們從頭開始一起加油?

mac 系統快速安裝

brew install openresty/brew/openresty

resty 命令

resty 命令快速測試

resty -e "ngx.say('hello world')"    output:  hello world

resty命令背後的操作

#查看 openstry 進程  ps -ef|grep openrestry    output:    /usr/local/Cellar/openresty/1.15.8.2/nginx/sbin/nginx  -p /tmp/resty_MnSJsgRCEI/  -c conf/nginx.conf

「我們看到有個 nginx 啟動進程, 其實內部執行了 nginx 命令, -p 指定了一個新的臨時目錄作為前綴路徑. 當進程執行完畢後自動銷毀

我們在代碼中加入 sleep 查看臨時目錄裏面存了些什麼

resty -e "os.execute('sleep '..12)  ngx.say('hello world')"

編寫項目

nginx.conf 配置中加入 lua 代碼

events {      worker_connections 1024;  }    http {      server {          listen 8080;          location /test {              content_by_lua '                  ngx.say("hello, world")              ';          }      }  }

我們使用 openresty 命令啟動項目

# 當前目錄作為前綴工作目錄啟動  openresty -p `pwd` -c conf/nginx.conf  # 重啟  openresty -s reload

我們可以使用 openresty -h 具體的參數含義

「-p 的含義可簡單理解為指定項目的工作目錄, -c 指定 nginx 配置.

curl 請求測試

curl -i http://127.0.0.1:8080/test    HTTP/1.1 200 OK  Server: openresty/1.15.8.2  Date: Sun, 10 Nov 2019 14:53:14 GMT  Content-Type: text/plain  Transfer-Encoding: chunked  Connection: keep-alive    hello, world

content_by_lua_file

上面例子我們的 lua 代碼和 nginx 配置耦合混用在一起, 這不是一個好的習慣.

下面我們通過調用 lua 腳本文件的方式來實現簡單輸出

nginx.conf

location /test {      content_by_lua_file lua/test.lua;  }

我們看到 content_by_lua_file 指定了相對目錄下的 lua/test.lua 文件, 那具體 lua 絕對目錄應該建在什麼地方呢?

我們可以通過 restydoc 命令快速查看下 content_by_lua_file 的解釋:

「通過上圖我們看到了這個參數的語法和作用域, 還記得上面我們在啟動服務的時候指定了 -p 參數, 工作目錄前綴參數, 他會從這個目錄下去找 lua目錄下的 test.lua

如果我們想換成其他路徑可以使用絕對路徑

location /test {      content_by_lua_file /Users/xxxx/Desktop/kong/lua/test.lua;  }

繼續看上圖發現 content_by_lua_file 還支持第二個參數, 也可以這樣使用

location /test {      lua_code_cache off;      content_by_lua_file test.lua /Users/wenba/Desktop/kong/lua;  }

如何讓你的 lua 代碼即時生效

我們發現每次修改完 lua 代碼,都需要重啟 openresty, 如果我們在開發環境中, 如何充分發揮出腳本的開發高效率呢?

我們可以使用 lua_code_cache 指令, 將它設置為關閉即可

location /test {      lua_code_cache off;      content_by_lua_file lua/test.lua;  }