本文链接: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 % ) +
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取模定向转发