Skip to content

Commit

Permalink
[redis] resolve redis host through internal dns resolver
Browse files Browse the repository at this point in the history
  • Loading branch information
mikz committed Jan 20, 2017
1 parent dfcbaed commit 3ad2b8c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- Cache all calls to `os.getenv` via custom module [PR #231](https://github.com/3scale/apicast/pull/231)
- Bump s2i-openresty to 1.11.2.2-1 [PR #239](https://github.com/3scale/apicast/pull/239)
- Use resty-resolver over nginx resolver for HTTP [PR #237](https://github.com/3scale/apicast/pull/237)
- Use resty-resolver over nginx resolver for Redis [PR #237](https://github.com/3scale/apicast/pull/237)

### Fixed
- [OAuth] Return correct state value back to client
Expand Down
28 changes: 27 additions & 1 deletion apicast/src/threescale_utils.lua
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@
local redis = require 'resty.redis'
local env = require 'resty.env'

local dns_resolver = require 'resty.resolver.dns'
local resty_resolver = require 'resty.resolver'
local resty_balancer = require 'resty.balancer'

local unpack = unpack

local _M = {} -- public interface

-- private
Expand Down Expand Up @@ -88,11 +94,31 @@ function _M.required_params_present(f_req, actual)
return true
end

local balancer = resty_balancer.new(function(peers) return peers[1] end)

function _M.resolve(host, port)
local dns = dns_resolver:new{ nameservers = resty_resolver.nameservers() }
local resolver = resty_resolver.new(dns)

local servers = resolver:get_servers(host, { port = port })
local peers = balancer:peers(servers)
local peer = balancer:select_peer(peers)

local ip = host

if peer then
ip, port = unpack(peer)
end

return ip, port
end

function _M.connect_redis(host, port)
local h = host or env.get('REDIS_HOST') or "127.0.0.1"
local p = port or env.get('REDIS_PORT') or 6379
local red = redis:new()
local ok, err = red:connect(h, p)

local ok, err = red:connect(_M.resolve(h, p))
if not ok then
return nil, _M.error("failed to connect to redis on " .. h .. ":" .. p .. ":", err)
end
Expand Down

0 comments on commit 3ad2b8c

Please sign in to comment.