class Redis::Directory
Constants
- DATABASES_KEY
- MAXIMUM_DATABASE_COUNT
Hard-coded, because I don’t know how to get this from the
Redis
connection at runtime.- SERVICES_KEY
Public Class Methods
new(connection_options)
click to toggle source
You must provide the connection_options
to the directory server.
# File lib/redis_directory.rb 28 def initialize(connection_options) 29 @redis = Redis.connect(connection_options) 30 end
Public Instance Methods
get(service_name, connection_name)
click to toggle source
# File lib/redis_directory.rb 64 def get(service_name, connection_name) 65 db = reserve(service_name, connection_name) 66 raise ReservationError.new(self, service_name, connection_name) if db.nil? 67 68 connection_list = services[service_name].map do |server| 69 if server =~ /^redis\:\/\// 70 "#{server}/#{db}" 71 else 72 "redis://#{server}/#{db}" 73 end 74 end 75 connection = nil 76 77 if connection_list.size == 1 78 connection = Redis.connect(:url => connection_list.first) 79 else 80 connection = Redis::Distributed.new(connection_list) 81 end 82 83 connection.set("connection-name", connection_name) 84 connection 85 end
next_db(service_name)
click to toggle source
This locates the next available database for a given service, starting at an index of 1. The 0 database is reserved in case you have a default connection, or local redis server (in which case 0 should be the directory database to avoid conflicts).
# File lib/redis_directory.rb 45 def next_db(service_name) 46 raise UndefinedServiceError.new(self, service_name) unless services.keys.include?(service_name) 47 databases = redis.hvals("#{service_name}-service").map { |i| i.to_i }.sort 48 (1..MAXIMUM_DATABASE_COUNT).select { |i| break i unless databases.include? i } 49 end
redis()
click to toggle source
# File lib/redis_directory.rb 87 def redis 88 @redis 89 end
reserve(service_name, connection_name)
click to toggle source
# File lib/redis_directory.rb 51 def reserve(service_name, connection_name) 52 new_db = nil 53 # redis.multi do 54 if redis.hexists("#{service_name}-service", connection_name) 55 new_db = redis.hget("#{service_name}-service", connection_name) 56 else 57 new_db = next_db(service_name) 58 redis.hset("#{service_name}-service", connection_name, new_db) 59 end 60 # end 61 new_db 62 end
services()
click to toggle source
# File lib/redis_directory.rb 32 def services 33 if redis.exists(SERVICES_KEY) 34 redis.hgetall(SERVICES_KEY).inject({}) do |h,(k,v)| 35 h[k] = JSON.parse(v); h 36 end 37 else 38 {} 39 end 40 end