• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

nginx基于lua语言进行开发

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

注:按照上一讲讲解的内容,基于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人参与评论

请发表评论

全部评论

专题导读
上一篇:
记一次Lua语言中死循环查错发布时间:2022-07-22
下一篇:
lua字符串格式化多参用法发布时间:2022-07-22
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap