Created
June 2, 2018 10:08
-
-
Save v-thomp4/3d5468e1e9b9c1cc3372c5672112bf7b to your computer and use it in GitHub Desktop.
nginx lua redis
This file contains hidden or 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
worker_processes 2; | |
error_log /var/log/nginx/error.log info; | |
events { | |
worker_connections 1024; | |
} | |
http { | |
init_by_lua ' | |
function split(inputstr, sep) | |
if inputstr == nil then | |
return {} | |
end | |
if sep == nil then | |
sep = "%s" | |
end | |
local t = {} | |
for str in string.gmatch(inputstr, "([^" .. sep .. "]+)") do | |
table.insert(t, str) | |
end | |
return t | |
end | |
'; | |
server { | |
listen 80; | |
location / { | |
resolver 8.8.4.4; # use Google's open DNS server | |
set $target ''; | |
access_by_lua ' | |
local key = ngx.var.http_host | |
if not key then | |
ngx.log(ngx.ERR, "no host found") | |
return ngx.exit(400) | |
end | |
local redis = require "resty.redis" | |
local r = redis:new() | |
r:set_timeout(1000) -- 1 second | |
local ok, err = r:connect("127.0.0.1", 6379) | |
if not ok then | |
ngx.log(ngx.ERR, "failed to connect to ris: ", err) | |
return ngx.exit(500) | |
end | |
local upstream_addrs, err = r:get(key) | |
if not upstream_addrs then | |
ngx.log(ngx.ERR, "failed to get redis key: ", err) | |
return ngx.exit(500) | |
end | |
if upstream_addrs == ngx.null then | |
ngx.log(ngx.ERR, "no host found for key ", key) | |
return ngx.exit(400) | |
end | |
upstream_addrs = split(upstream_addrs, ",") | |
local upstream_addr = upstream_addrs[math.random(#upstream_addrs)] | |
ngx.var.target = upstream_addr | |
'; | |
proxy_pass http://$target; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment