Skip to content

Instantly share code, notes, and snippets.

@Geesu
Created November 17, 2014 15:44
Show Gist options
  • Save Geesu/0870fddc999d87612ec1 to your computer and use it in GitHub Desktop.
Save Geesu/0870fddc999d87612ec1 to your computer and use it in GitHub Desktop.
module Aperture
module Redis
class Pool < ::ConnectionPool
attr_accessor :namespace
def initialize(options = {})
super(options.delete :pool) { ::Redis.new options }
end
def with_namespace(ns)
clone.tap { |o| o.namespace = ns }
end
def checkout(*args, &block)
conn = super(*args, &block)
if conn && namespace
return ::Redis::Namespace.new namespace, :redis => conn
end
conn
end
def wrap
Wrapper.new self
end
class Wrapper < ::ConnectionPool::Wrapper
def initialize(pool)
@pool = pool
end
end
end
def self.pool(pool_size = 50)
@pool_size = pool_size
@pool = Pool.new config
end
private
def self.config
{
:url => url,
:timeout => 10.0,
:pool => { :size => pool_size }
}
end
def self.pool_size
case
when ::Sidekiq.server? then
Sidekiq.options[:concurrency] + 2
else
@pool_size || 50
end
end
def self.url
@url ||= Rails.configuration.redis.url || fail("No Redis URL given in config/redis.yml")
end
end
def self.redis(*args, &block)
return Redis.pool.wrap unless block_given?
Redis.pool(*args, &block)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment