公司业务前端是使用 "分发层 + 应用层" 双层 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 取模定向转发
来源: http://www.bubuko.com/infodetail-2629956.html