Nginx+Lua 定制流量分发策略案例

4 篇文章 0 订阅
准备3台机器 eshop-cache01、eshop-cache02、eshop-cache03,用 eshop-cache01 和 eshop-cache02 作为应用层 Nginx服务器,用 eshop-cache03 作为分发层 Nginx。在 eshop-cache03,也就是分发层 Nginx 中,编写 Lua脚本,完成基于 商品id 的流量分发策略
1> 获取请求参数,比如 productId
2> 对 productId 进行 hash
3> hash值 对应用服务器数量取模,获取到一个应用服务器
4> 利用 http 发送请求到应用层 nginx
5> 获取响应后返回
基于商品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.1s

2018-05-10 21:24:34 (239 KB/s) - 已保存 “http.lua” [29686/29686])

创建 hellow.lua 脚本
`hellow.lua

-- 获取访问参数中的 productId
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)
hash = (hash % 2) + 1
backend = "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)
    return
end

-- 访问成功返回对应信息
ngx.say(resp.body)

-- 关闭访问请求
httpc:close()

重新加载所有配置,包括 Lua 脚本
# cd /opt/modules/openresty/nginx
# ./sbin/nginx -t
# ./sbin/nginx -s reload
基于商品id的定向流量分发策略的 Lua脚本就开发完了,如果请求的是固定的某一个商品,那么就一定会将流量打到固定的一个应用 Nginx 上面去 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值