上篇博文我們已經基於OpenResty搭建了Nginx+Lua的運行環境,並且編寫了工程小Demo,本博文將基於上篇博文的環境來繼續實現Nginx+Lua是實現定向請求分發
參考之前的博文
- SpringBoot+Redis+MemCache+Nginx+Lua實現三級緩存架構(一)——三級緩存架構體系
- SpringBoot+Redis+MemCache+Nginx+Lua實現三級緩存架構(二)——Nginx環境安裝和整合Lua
請求定向實現的原理
在實現定向請求分發的功能之間,我們先了解下具體的實現的原理和邏輯
業務邏輯如下:
- 分發層獲取請求的關鍵字段,比如id
- 對id進行hash
- hash值對應用服務器數量進行取模,獲取到啓動的其中的一個應用服務器
- 利用http發送請求到應用層
- 獲取返回後的結果
環境完善
上一篇博文中,我們已經在一個服務器上搭建了環境,接下來我們需要再準備兩個環境,總共是三個環境:
服務器 | 用途 |
---|---|
192.168.56.105 | 分發層 |
192.168.56.106 | 應用層 |
192.168.56.107 | 應用層 |
按照SpringBoot+Redis+MemCache+Nginx+Lua實現三級緩存架構(二)——Nginx環境安裝和整合Lua的方法來搭建餘下的兩個環境,並且測試是否聯通
代碼開發
現在開始編寫lua的代碼,由於我們分發層需要使用http來請求其他的Nginx服務,所以我們需要先將http的依賴加載起來
## 在lualib下的resty下面來加載http的依賴
cd /home/work/lualib/resty
## 下載http_headers.lua
wget https://raw.githubusercontent.com/pintsized/lua-resty-http/master/lib/resty/http_headers.lua
wget https://raw.githubusercontent.com/pintsized/lua-resty-http/master/lib/resty/http.lua
下面我們開始開發,在分發層的 /home/work/conf/lua/requestDirect.lua
中編寫如下的代碼
-- 獲取請求的url地址
local uri_args = ngx.req.get_uri_args()
-- 獲取請求中的參數id的值
local id = uri_args["id"]
-- 目前我們準備了兩個應用的nginx服務,所以我們獲取應用層的ip爲對象
local hosts = {"192.168.56.106","192.168.56.107"}
-- 對id記性hash
local hash = ngx.crc32_long(id)
-- hash值對應用層服務器的數量取模+1
hash = (hash % 2) + 1
-- 拼接需要訪問應用層的url地址 http://192.168.56.107
backend = "http://"..hosts[hash]
-- 獲取url地址中的參數 requestPath 這個路徑是訪問應用層的
-- 在本文搭建的過程中 ,主要是應用層中的 /home/work/conf/nginx.conf
-- 中的訪問地址
local requestPath = uri_args["requestPath"]
-- 拼接url地址後面的請求參數 http://192.168.56.107/lua?id=1
requestPath = "/"..requestPath.."?id="..id
-- 加載http
local http = require("resty.http")
-- 創建http的客戶端
local httpc = http.new()
-- 執行url請求
local resp, err = httpc:request_uri(backend,{
method = "GET",
path = requestPath
})
-- 如果失敗,則返回前臺失敗的消息
if not resp then
ngx.say("request error:", err)
return
end
-- 如果請求成功,打印請求內容
ngx.say(resp.body)
-- http客戶端關閉
httpc:close()
代碼開發完成之後, 我們重新加載下
## 編譯
nginx -t
## 重新加載
nginx -s reload
在瀏覽器上請求:
# 請求一 requestPath的路徑目前只能是lua,爲了請求到
## 應用Nginx層的lua訪問
http://192.168.56.105/lua?requestPath=lua&id=1
http://192.168.56.105/lua?requestPath=lua&id=2
可以變更id的值,看看請求返回的值有很什麼變化
如果在執行的過程中,出現錯誤了,可以查看nginx的日誌記錄
## 查看 nginx的錯誤日誌
tail -1000f /usr/local/openresty/nginx/logs/error.log
至此我們就全部完成了定向請求分發的功能,下一篇博文,我們結合後臺框架來整合nginx和redis以及tomcat堆緩存的交互,完成三級緩存架構的功能