Last active
July 28, 2024 14:01
-
-
Save dome/fc4ca2daea397f79f42dd0ed4c8fba7a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#-- nginx.conf: | |
events { | |
worker_connections 10240; | |
} | |
http { | |
lua_socket_log_errors off; #-- don't clutter the error log when upstream severs fail | |
lua_shared_dict hosts 10m; | |
init_by_lua_block { | |
local hosts = ngx.shared.hosts | |
local hosts_keys = hosts:get_keys() | |
} | |
server { | |
listen 8080; | |
location / { | |
set $proxy_host '' ; | |
access_by_lua_block { | |
local hosts = ngx.shared.hosts | |
local hosts_keys = hosts:get_keys() | |
local total_weight = 0 | |
for i, key in ipairs(hosts_keys) do | |
total_weight = total_weight + hosts:get(key) | |
end | |
local random_num = math.random(1, total_weight) | |
total_weight = 0 | |
for i, key in ipairs(hosts_keys) do | |
total_weight = total_weight + hosts:get(key) | |
--ngx.say(random_num) | |
--ngx.say(key) | |
if random_num <= total_weight then | |
--ngx.say(key) | |
ngx.var.proxy_host = key | |
break | |
end | |
end | |
} | |
proxy_set_header Host $proxy_host; | |
proxy_pass http://127.0.0.1:2121; | |
} | |
} | |
server { | |
listen 8081; | |
server_name _; | |
location = /add-host { | |
content_by_lua_block { | |
-- Getting post request body | |
ngx.req.read_body() | |
local cjson = require "cjson" | |
local post_args = ngx.req.get_post_args() | |
local json_str = next(post_args) | |
local json_obj = cjson.decode(json_str) | |
local host = json_obj.host | |
local weight = json_obj.weight | |
local hosts = ngx.shared.hosts | |
hosts:set(host, weight) | |
ngx.say(host) | |
ngx.say(hosts:get(host)) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment