你们能够本身按照上一讲讲解的内容,基于OpenResty在另外两台机器上都部署一下nginx+lua的开发环境nginx
我已经在eshop-cache02和eshop-cache03上都部署好了git
我这边的话呢,是打算用eshop-cache01和eshop-cache02做为应用层nginx服务器,用eshop-cache03做为分发层nginxgithub
在eshop-cache03,也就是分发层nginx中,编写lua脚本,完成基于商品id的流量分发策略后端
固然了,咱们这里主要会简化策略,简化业务逻辑,实际上在你的公司中,你能够随意根据本身的业务逻辑和场景,去制定本身的流量分发策略服务器
一、获取请求参数,好比productId
二、对productId进行hash
三、hash值对应用服务器数量取模,获取到一个应用服务器
四、利用http发送请求到应用层nginx
五、获取响应后返回测试
这个就是基于商品id的定向流量分发的策略,lua脚原本编写和实现ui
咱们做为一个流量分发的nginx,会发送http请求到后端的应用nginx上面去,因此要先引入lua http lib包lua
cd /usr/hello/lualib/resty/
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.luarest
keepalive=false,必需要加,否则会报错
代码:server
local uri_args = ngx.req.get_uri_args()
local productId = uri_args["productId"]
local host = {"192.168.31.19", "192.168.31.187"}
local hash = ngx.crc32_long(productId)
hash = (hash % 2) + 1
backend = "http://"..host[hash]
local method = uri_args["method"]
local requestBody = "/"..method.."?productId="..productId
local http = require("resty.http")
local httpc = http.new()
local resp, err = httpc:request_uri(backend, {
method = "GET",
path = requestBody,
keepalive=false
})
if not resp then
ngx.say("request error :", err)
return
end
ngx.say(resp.body)
httpc:close()
/usr/servers/nginx/sbin/nginx -s reload
http://192.168.194.133/hello?requestPath=hello&productId=1
基于商品id的定向流量分发策略的lua脚本就开发完了,并且也测试过了
咱们就能够看到,若是你请求的是固定的某一个商品,那么就必定会将流量打到固定的一个应用nginx上面去