解決問題:負載均衡的時候,假如業務邏輯主機有四臺(A,B,C,D),雖然配置ip_hash(ji),這只是實現同一個ip去請求一個上層業務服務器(能夠解決session的問題),可是如今,若是要實現一個商品頁面的緩存內容只緩存在一臺服務器A (全部關於這個頁面請求都丟給A服務器,BCD服務器沒有關於這個頁面的緩存內容),極大程度的節省了服務器的存儲空間。php
首先查看當前服務器的版本:nginx -V (注:根據個人測試,能夠增長 lua 模塊的版本對也nginx的版本有要求,最低版本是:nginx/1.6.0)nginx
安裝Lua,和這個業務中須要相應的代碼包模塊:git
wget http://luajit.org/download/LuaJIT-2.0.5.tar.gz github
tar -zxvf LuaJIT-2.0.5.tar.gz緩存
cd LuaJIT-2.0.5服務器
make install PREFIX=/usr/local/LuaJITswoole
export LUAJIT_LIB=/usr/local/LuaJIT/lib session
export LUAJIT_INC=/usr/local/LuaJIT #路徑是上面luajit實際安裝路徑,路徑錯誤安裝nginx的lua模塊時會報錯很找不到luajit庫負載均衡
下載相應的模塊:測試
wget https://github.com/simpl/ngx_devel_kit/archive/v0.3.0.tar.gz
2.下載lua-nginx-module模塊
wget https://github.com/openresty/lua-nginx-module/archive/v0.10.9rc7.tar.gz
解壓後,從新編譯nginx 引入相應的模塊:
--add-module=/root/nginx-lua/lua-nginx-module-0.10.9rc7 --add-module=/root/nginx-lua/ngx_devel_kit-0.3.0
編寫相應的nginx 配置(記得執行:nginx -s reload 否在配置不生效)
upstream.lua的代碼編寫:
local uri_args=ngx.req.get_uri_args() local id=uri_args["id"] local server={"193.45.126.217:9502","193.45.126.217:9503"} local hash=ngx.crc32_long(id) local index=(hash % table.getn(server))+1 url="http://"..server[index] local http=require("resty.http") local httpClient=http.new() local resp,err = httpClient:request_uri(url,{method="GET"}) if not resp then ngx.say(err) return end ngx.say(resp.body) httpClient:close()
爲了方便測試,我用Swoole建立了兩臺http服務器,分別是端口9502,9503http服務器。
9502Http服務器
<?php $http=new swoole\http\server('0.0.0.0',9502); $http->on('request',function ($request, $response){ $response->end('<h1>9502:'.date('m-d H:i:s').'</h1>'); }); $http->start();
9503Http服務器
<?php $http=new swoole\http\server('0.0.0.0',9503); $http->on('request',function ($request, $response){ var_dump($request); $response->end('<h1>9502:'.date('m-d H:i:s').'</h1>'); }); $http->start();