nginx基于lua语言进行开发

注:按照上一讲讲解的内容,基于OpenResty在另外两台机器上都部署一下nginx+lua的开发环境,192.168.25.103和192.168.25.104上都部署好了,这边的话呢,是打算用192.168.25.103和192.168.25.104作为应用层nginx服务器,用192.168.25.102作为分发层nginx,
在192.168.25.102,也就是分发层nginx中,编写lua脚本,完成基于商品id的流量分发策略

在这里插入图片描述

主要思路:

1、获取请求参数,比如productId
2、对productId进行hash
3、hash值对应用服务器数量取模,获取到一个应用服务器
4、利用http发送请求到应用层nginx
5、获取响应后返回
  这个就是基于商品id的定向流量分发的策略,lua脚本来编写和实现
1.导包

我们作为一个流量分发的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 
2.代码

编辑 /usr/hello/lua/hello.conf 文件编写代码

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() 
3.重启下nginx
/usr/servers/nginx/sbin/nginx -s reload
4.测试
访问:http://192.168.25.102/hello?method=hello&productId=4  
改变productId  你会发现分发到不同的应用层去
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值