简单版nginx lua 完成定向流量分发策略

本文链接:https://www.cnblogs.com/zhenghongxin/p/9131362.html

公司业务前端是使用 “分发层+应用层” 双层nginx架构,目的是为了提高缓存的命中率。最前端有个nginx分发层,底下是负载均衡集群。

为了提高缓存的命中率,需要nginx进行定向流量分发,简略代码如下:

local uri_args = ngx.req.get_uri_args()
local productId = uri_args["productId"]

local hosts = {"192.168.31.187", "192.168.31.19"}
local hash = ngx.crc32_long(productId)
local index = (hash % 2) + 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()

 进行hash取模定向转发

posted @ 2018-06-03 23:56  hongxinerke  阅读(1915)  评论(3编辑  收藏  举报