Last active
April 19, 2017 20:35
-
-
Save Mitendra/b2eeebaac135ee1179949e66f703818b to your computer and use it in GitHub Desktop.
load balancing using lua
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
| REDIS_HOST = "127.0.0.1" | |
| REDIS_PORT = "6379" | |
| DEFAULT_UPSTREAM_SERVER = "127.0.0.1" | |
| local redis = require "resty.redis" | |
| local red = redis:new() | |
| red:set_timeout(1000) -- 1 second | |
| local ok, err = red:connect(REDIS_HOST,REDIS_PORT) | |
| if not ok then | |
| ngx.var.target = DEFAULT_UPSTREAM_SERVER | |
| else | |
| local key = "service_discovery" | |
| -- Services are idenified by the port they listen to. | |
| -- Can also be identified by service name or any other information which can be extracted from the request | |
| local host_list_str, err = red:hmget(key, ngx.var.server_port) | |
| if not host_list_str or host_list_str[1] == ngx.null then | |
| ngx.var.target = DEFAULT_UPSTREAM_SERVER | |
| else | |
| local hosts = {} | |
| local index = 1 | |
| -- Comma seperated host list for a given service | |
| for value in string.gmatch(host_list_str[1], "[^,]+") do | |
| hosts[index] = value | |
| index = index + 1 | |
| end | |
| -- Pick a random host, assuming randomness will also bring some form of roundrobin-ness | |
| ngx.var.target = hosts[math.random(#hosts)] | |
| ngx.log(ngx.ERR, "selected host is: " .. ngx.var.target) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment