1 nginx_url_hash
Nginx第三方模块,如果后端服务器宕机会发生503,使用也不灵活
2 lua-resty-http
下载lua-resty-http
git 地址:https://github.com/pintsized/lua-resty-http
将http.lua,http_connect.lua,http_headers.lua三个文件拷贝到/app/openresty/lualib/resty目录下
local http = require("resty.http")
local httpc = http.new()
local resp, err = httpc:request_uri("http://10.10.100.24:8762", {
method = "GET",
path = "/sparksql/get/databases",
headers = {
["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36"
}
})
if not resp then
ngx.say("request error :", err)
return
end
ngx.status = resp.status
for k, v in pairs(resp.headers) do
if k ~= "Transfer-Encoding" and k ~= "Connection" then
ngx.header[k] = v
end
end
ngx.say(resp.body)
httpc:close()
编辑nginx配置文件
location /restyhttp {
default_type text/html;
content_by_lua_file /app/openresty/luascript/restyhttp.lua;
}
假如访问外网需要加nginx中假如dns地址
在nginx配置文件http模块中加入
resolver 8.8.8.8;
3 lua-resty-http根据url参数进行进行负载均衡
local http = require("resty.http")
local httpc = http.new()
local hosts = {"10.10.100.24:8762","10.10.100.24:8762"} -- 模拟测试两个IP
local item_id= ngx.var.arg_id -- url中传入参数名为id
local id_hash = ngx.crc32_long(item_id)
local index = (id_hash % 2) +1
local resp, err = httpc:request_uri("http://"..hosts[index], {
method = "GET",
path = "/sparksql/get/databases",
headers = {
["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36"
}
})
if not resp then
ngx.say("request error :", err)
return
end
ngx.status = resp.status
for k, v in pairs(resp.headers) do
if k ~= "Transfer-Encoding" and k ~= "Connection" then
ngx.header[k] = v
end
end
ngx.say(resp.body)
httpc:close()