1. 程式人生 > >nginx+lua (二)請求分發

nginx+lua (二)請求分發

product include new fault 腳本 back () file res

比如對產品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;

nginx+lua (二)請求分發