2.nginx流量分发服务器部署

使用cache03作为流量分发服务器,cache02和cache01作为应用服务器
nginx日志目录 /usr/servers/nginx/logs
想法:
1、获取请求参数,比如productId
2、对productId进行hash
3、hash值对应用服务器数量取模,获取到一个应用服务器
4、利用http发送请求到应用层nginx
5、获取响应后返回


这个就是基于商品id的定向流量分发的策略,lua脚本来编写和实现


在cache03上操作:


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


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.lua 






vi /usr/hello/hello.conf


修改location /hello
访问的时候 使用hello,根据业务自己改
例如:
server {
    listen       80;
    server_name  _;


    location /product {
        default_type 'text/html';
        content_by_lua_file /usr/hello/lua/test.lua;
    }


    location /hot {
        default_type 'text/html';
        content_by_lua_file /usr/hello/lua/hot.lua;
    }


    location /cancel_hot {
        default_type 'text/html';
        content_by_lua_file /usr/hello/lua/cancel_hot.lua;
    }


}








vi /usr/hello/lua/test.lua


local uri_args = ngx.req.get_uri_args()
local productId = uri_args["productId"]
local host = {"139.199.10.125", "111.230.234.30"}
local hash = ngx.crc32_long(productId)
hash = (hash % 2) + 1
backend = "http://"..host[hash]
local requestPath = uri_args["requestPath"]
local requestBody = "/"..requestPath.."?productId="..productId
local http = require("resty.http")
local httpc = http.new()
local resp, err = httpc:request_uri(backend, {
    method = "GET",
    path = requestBody
})
if not resp then
    ngx.say("request error :", err)
    return
end
ngx.say(resp.body)
httpc:close()





重新nginx加载配置
/usr/servers/nginx/sbin/nginx -s reload  


访问:http://139.199.6.253/product?requestPath=hello&productId=7
http://139.199.6.253/product?requestPath=product&productId=1&shopId=1
发现测试成功,根据productId路由到不同的nginx服务器



















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值