本文共 2703 字,大约阅读时间需要 9 分钟。
准备3台机器 eshop-cache01、eshop-cache02、eshop-cache03,用 eshop-cache01 和 eshop-cache02 作为应用层 Nginx服务器,用 eshop-cache03 作为分发层 Nginx。在 eshop-cache03,也就是分发层 Nginx 中,编写 Lua脚本,完成基于 商品id 的流量分发策略
3> hash值 对应用服务器数量取模,获取到一个应用服务器
4> 利用 http 发送请求到应用层 nginx
基于商品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] 100%[==============================================================================================================================================>] 29,686 --.-K/s 用时 0.1s 2018-05-10 21:24:34 (239 KB/s) - 已保存 “http.lua” [29686/29686]) local 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) backend = "http://" .. host[hash] local method = uri_args["method"] local fullUri = backend .. "/" .. method .. "?productId=" .. productId local http = require("resty.http") local resp, err = httpc:request_uri(fullUri, { ngx.say("request error :", err) # cd /opt/modules/openresty/nginx 基于商品id的定向流量分发策略的 Lua脚本就开发完了,如果请求的是固定的某一个商品,那么就一定会将流量打到固定的一个应用 Nginx 上面去
转载地址:http://yogab.baihongyu.com/