Skip to content

Instantly share code, notes, and snippets.

@un-def
Created March 22, 2019 12:35
Show Gist options
  • Save un-def/1821d0b6c34e20a3cb480f23b0df4ba3 to your computer and use it in GitHub Desktop.
Save un-def/1821d0b6c34e20a3cb480f23b0df4ba3 to your computer and use it in GitHub Desktop.
nginx lua balancer example
return {
servers = {
foo = {'127.0.0.1', 9001},
bar = {'127.0.0.1', 9002},
baz = {'127.0.0.1', 9003},
}
}
daemon off;
worker_processes 1;
pid nginx.bar.pid;
error_log stderr debug;
events {
worker_connections 1024;
}
stream {
lua_code_cache off;
init_by_lua_block {
require('ngx.balancer')
require('server')
require('config')
}
server {
listen 9002;
proxy_pass dispatcher;
preread_by_lua_block {
require('server').serve('bar')
}
}
upstream dispatcher {
server 0.0.0.1:1234;
balancer_by_lua_block {
require('server').dispatch()
}
}
}
daemon off;
worker_processes 1;
pid nginx.baz.pid;
error_log stderr debug;
events {
worker_connections 1024;
}
stream {
lua_code_cache off;
init_by_lua_block {
require('ngx.balancer')
require('server')
require('config')
}
server {
listen 9003;
proxy_pass dispatcher;
preread_by_lua_block {
require('server').serve('baz')
}
}
upstream dispatcher {
server 0.0.0.1:1234;
balancer_by_lua_block {
require('server').dispatch()
}
}
}
daemon off;
worker_processes 1;
pid nginx.foo.pid;
error_log stderr debug;
events {
worker_connections 1024;
}
stream {
lua_code_cache off;
init_by_lua_block {
require('ngx.balancer')
require('server')
require('config')
}
server {
listen 9001;
proxy_pass dispatcher;
preread_by_lua_block {
require('server').serve('foo')
}
}
upstream dispatcher {
server 0.0.0.1:1234;
balancer_by_lua_block {
require('server').dispatch()
}
}
}
local balancer = require('ngx.balancer')
local config = require('config')
local servers = config.servers
local _M = {}
local answer = function(own_id, ...)
ngx.say('[', own_id, '] ', ...)
end
local log_err = function(...)
args = {...}
table.insert(args, '\n\n')
ngx.log(ngx.ERR, '\n\n*** ', table.unpack(args))
end
_M.serve = function(own_id)
answer(own_id, 'connected')
local sock = ngx.req.socket()
while true do
local data, err = sock:receive('*l')
if not data then
log_err('read error: ', err)
ngx.exit(ngx.ERROR)
end
if data:sub(1, 1) == '/' then
local upstream_id = data:sub(2)
answer(own_id, 'connecting to upstream: ', upstream_id)
ngx.ctx.upstream_id = upstream_id
ngx.exit(ngx.OK)
else
answer(own_id, 'echo: ', data)
end
end
end
_M.dispatch = function()
local upstream_id = ngx.ctx.upstream_id
local upstream = servers[upstream_id]
if not upstream then
log_err('unknown upstream: ', upstream_id)
ngx.exit(ngx.ERROR)
else
local ok, err = balancer.set_current_peer(table.unpack(upstream))
if not ok then
log_err('failed to set upstream: ', err)
ngx.exit(ngx.ERROR)
end
end
end
return _M
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment