Nginx分发层部署以及基于lua完成基于商品id的定向流量分发策略

发布 : 2017-07-09 分类 : 大数据 浏览 :
1
2
3
192.168.31.231 matrix-cache01
192.168.31.232 matrix-cache02
192.168.31.233 matrix-cache03
1
2
matrix-cache01和matrix-cache02为应用层nginx服务器
matrix-cache03作为分发层nginx,编写lua脚本,完成基于商品id的流量分发策略

作为一个流量分发的nginx,会发送http请求到后端的应用nginx上面去,需要引入lua http lib包

1
2
3
[root@matrix-cache03 ~]# cd /usr/hello/lualib/resty/
[root@matrix-cache03 lualib]# wget https://raw.githubusercontent.com/pintsized/lua-resty-http/master/lib/resty/http_headers.lua
[root@matrix-cache03 lualib]# wget https://raw.githubusercontent.com/pintsized/lua-resty-http/master/lib/resty/http.lua
1
[root@matrix-cache03 ~]# vi /usr/hello/lua/hello.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
local uri_args = ngx.req.get_uri_args()
local productId = uri_args["productId"]

local hosts = {"192.168.31.231","192.168.31.232"}
local hash = ngx.crc32_long(productId)
local index = (hash % 1) + 1
backend = "http://"..hosts[index]

local requestPath = uri_args["requestPath"]
requestPath = "/"..requestPath.."?productId="..productId

local http = require("resty.http")
local httpc = http.new()

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)

httpc:close()
1
2
3
基于商品id的定向流量分发策略的lua脚本

请求的如果是固定的某一个商品,那么就一定会将流量打到固定的一个应用nginx上面去

重新nginx加载配置

1
[root@matrix-cache03 ~]# /usr/servers/nginx/sbin/nginx -s reload

在浏览器地址栏中请求某个固定商品

1
http://192.168.31.233/hello?requestPath=hello&productId=1

查看Nginx错误日志

1
[root@matrix-cache03 ~]# tail -f /usr/servers/nginx/logs/error.log

本文作者 : Matrix
原文链接 : https://matrixsparse.github.io/2017/07/09/Nginx分发层部署以及基于lua完成基于商品id的定向流量分发策略/
版权声明 : 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!

知识 & 情怀 | 二者兼得

微信扫一扫, 向我投食

微信扫一扫, 向我投食

支付宝扫一扫, 向我投食

支付宝扫一扫, 向我投食

留下足迹