nginx+lua (二)请求分发

比如对产品productId=143这个请求分发

现编写lua脚本

distrib_product.lua

local uri_args = ngx.req.get_uri_args()
local productId = uri_args["productId"]
--获取链接地址 和 productId参数
local hosts = {"172.16.95.145","172.16.95.146","172.16.95.147"}
local hash = ngx.crc32_long(productId)
local hosts_cnt = #hosts
local index = (hash % hosts_cnt) + 1
--分发的主机地址 对参数取模
backend = "http://"..hosts[index]

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
})

if not resp then
ngx.say("requst err:",err)
return
end

ngx.say(resp.body)
httpc:close()

新建配置文件

distrib.conf 

server {
  listen 80;
  server_name _;

  location /dis {
    default_type 'text/html';
    #lua_code_cache off;
    content_by_lua_file /usr/distrib_product/lua/distrib_product.lua;
  }
}

在 ngix.conf 中 include         /usr/distrib_product/distrib.conf;

原文地址:https://www.cnblogs.com/qingducx/p/7636230.html