Skip to content

Instantly share code, notes, and snippets.

@PatrickTulskie
Created June 7, 2013 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PatrickTulskie/5731013 to your computer and use it in GitHub Desktop.
Save PatrickTulskie/5731013 to your computer and use it in GitHub Desktop.
Waterfall connector for Redis in Ruby
class RedisConnector
def self.connection
return $redis if $redis
case Rails.env
when /production/
# Don't use waterfall connection here because we don't want
# production inconsistencies
connect_with_failover
when /(development)|(staging)/
# Connect with waterfall to allow for dev/staging flexibility
connect_with_waterfall
when 'test'
redis_connection = connect_with_waterfall(:db => 15)
prepare_test_database(redis_connection)
return redis_connection
end
end
def self.connect_with_waterfall(options = { })
begin
redis_connection = connect_with_failover(options)
redis_connection.client.discover_master
puts "Notice: Connected to Redis with failover support via Redis Sentinel"
rescue Exception, RuntimeError
redis_connection = connect_without_failover(options)
puts "Notice: Connected to Redis without failover support"
end
return redis_connection
end
def self.connect_with_failover(options = { })
sentinel_config = YAML.load_file(File.join(Rails.root, 'config', 'redis_sentinel.yml'))[Rails.env]
sentinels = sentinel_config['sentinels'].map { |server| server.symbolize_keys }
Redis.new(
options.merge(
:master_name => sentinel_config['master_name'],
:sentinels => sentinels,
:failover_reconnect_timeout => sentinel_config['reconnect_timeout'],
:master_discover_attempts => sentinel_config['master_discover_attempts']
)
)
end
def self.connect_without_failover(options = { })
redis_config = YAML.load_file(File.join(Rails.root, 'config', 'redis.yml'))
redis_server, redis_port = *redis_config[Rails.env].split(':')
Redis.new(options.merge(:host => redis_server, :port => redis_port))
end
def self.prepare_test_database(redis_connection)
redis_connection.flushdb
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment