thread-safe connection handler

This commit is contained in:
2011-04-14 16:53:29 +01:00
parent f155f6db05
commit 0a7abe935e
2 changed files with 39 additions and 14 deletions

View File

@@ -1,29 +1,41 @@
require 'monitor'
module Redistat
module Connection
REQUIRED_SERVER_VERSION = "1.3.10"
# TODO: Create a ConnectionPool instance object to replace Connection class
class << self
# TODO: clean/remove all ref-less connections
def get(ref = nil)
ref ||= :default
connections[references[ref]] || create
synchronize do
connections[references[ref]] || create
end
end
def add(conn, ref = nil)
ref ||= :default
check_redis_version(conn)
references[ref] = conn.client.id
connections[conn.client.id] = conn
synchronize do
check_redis_version(conn)
references[ref] = conn.client.id
connections[conn.client.id] = conn
end
end
def create(options = {})
#TODO clean/remove all ref-less connections
ref = options.delete(:ref) || :default
options.reverse_merge!(default_options)
conn = (connections[connection_id(options)] ||= connection(options))
references[ref] = conn.client.id
conn
synchronize do
options = options.clone
ref = options.delete(:ref) || :default
options.reverse_merge!(default_options)
conn = (connections[connection_id(options)] ||= connection(options))
references[ref] = conn.client.id
conn
end
end
def connections
@@ -36,9 +48,12 @@ module Redistat
private
def check_redis_version(conn)
raise RedisServerIsTooOld if conn.info["redis_version"] < REQUIRED_SERVER_VERSION
conn
def monitor
@monitor ||= Monitor.new
end
def synchronize(&block)
monitor.synchronize(&block)
end
def connection(options)
@@ -46,10 +61,15 @@ module Redistat
end
def connection_id(options = {})
options.reverse_merge!(default_options)
options = options.reverse_merge(default_options)
"redis://#{options[:host]}:#{options[:port]}/#{options[:db]}"
end
def check_redis_version(conn)
raise RedisServerIsTooOld if conn.info["redis_version"] < REQUIRED_SERVER_VERSION
conn
end
def default_options
{
:host => '127.0.0.1',

View File

@@ -59,4 +59,9 @@ describe Redistat::Connection do
Redistat.connect(:port => 8379, :db => 15)
end
# TODO: Test thread-safety
it "should be thread-safe" do
pending("need to figure out a way to test thread-safety")
end
end