1. 程式人生 > >Nginx+Lua 定製流量分發策略案例

Nginx+Lua 定製流量分發策略案例

準備3臺機器 eshop-cache01、eshop-cache02、eshop-cache03,用 eshop-cache01 和 eshop-cache02 作為應用層 Nginx伺服器,用 eshop-cache03 作為分發層 Nginx。在 eshop-cache03,也就是分發層 Nginx 中,編寫 Lua指令碼,完成基於 商品id 的流量分發策略1> 獲取請求引數,比如 productId2> 對 productId 進行 hash3> hash值 對應用伺服器數量取模,獲取到一個應用伺服器4> 利用 http 傳送請求到應用層 nginx5> 獲取響應後返回基於商品id的定向流量分發的策略,Lua指令碼來編寫和實現作為一個流量分發的 Nginx,會發送 http請求到後端的應用 Nginx 上面去,所以要先引入 lua http lib包(一個網路請求的庫)# cd /opt/modules/openresty/lualib/resty# wget https://raw.githubusercontent.com/pintsized/lua-resty-http/master/lib/resty/http_headers.lua--2018-05-10 21:23:25--  https://raw.githubusercontent.com/pintsized/lua-resty-http/master/lib/resty/http_headers.lua正在解析主機 raw.githubusercontent.com (raw.githubusercontent.com)... 151.101.72.133
正在連線 raw.githubusercontent.com (raw.githubusercontent.com)|151.101.72.133|:443... 已連線。已發出 HTTP 請求,正在等待迴應... 200 OK長度:1150 (1.1K) [text/plain]正在儲存至: “http_headers.lua”100%[==============================================================================================================================================>] 1,150       --.-K/s 用時 0s
2018-05-10 21:23:27 (262 MB/s) - 已儲存 “http_headers.lua” [1150/1150])# wget https://raw.githubusercontent.com/pintsized/lua-resty-http/master/lib/resty/http.lua--2018-05-10 21:24:33--  https://raw.githubusercontent.com/pintsized/lua-resty-http/master/lib/resty/http.lua正在解析主機 raw.githubusercontent.com (raw.githubusercontent.com)... 151.101.72.133
正在連線 raw.githubusercontent.com (raw.githubusercontent.com)|151.101.72.133|:443... 已連線。已發出 HTTP 請求,正在等待迴應... 200 OK長度:29686 (29K) [text/plain]正在儲存至: “http.lua”100%[==============================================================================================================================================>] 29,686      --.-K/s 用時 0.1s2018-05-10 21:24:34 (239 KB/s) - 已儲存 “http.lua” [29686/29686])建立 hellow.lua 指令碼`hellow.lua-- 獲取訪問引數中的 productIdlocal uri_args = ngx.req.get_uri_args()local productId = uri_args["productId"]-- 通過對 productId 的 hash 計算,獲取對應伺服器地址local host = { "192.168.31.19", "192.168.31.187" }local hash = ngx.crc32_long(productId)hash = (hash % 2) + 1backend = "http://" .. host[hash]-- 將訪問路徑拼接成相應的訪問地址local method = uri_args["method"]local fullUri = backend .. "/" .. method .. "?productId=" .. productId-- 重新進行訪問local http = require("resty.http")local httpc = http.new()local resp, err = httpc:request_uri(fullUri, {    method = "GET"})-- 訪問失敗報錯if not resp then    ngx.say("request error :", err)    returnend-- 訪問成功返回對應資訊ngx.say(resp.body)-- 關閉訪問請求httpc:close()重新載入所有配置,包括 Lua 指令碼# cd /opt/modules/openresty/nginx# ./sbin/nginx -t# ./sbin/nginx -s reload基於商品id的定向流量分發策略的 Lua指令碼就開發完了,如果請求的是固定的某一個商品,那麼就一定會將流量打到固定的一個應用 Nginx 上面去