PooledRedis
Simple way to access redis connections without global variables.
Provides Rails.redis_pool & Rails.redis methods and configuration via database.yml.
You can add this methods to custom modules.
Installation
Add this line to your application's Gemfile:
gem 'pooled_redis'Usage
- Add
redissection to yourdatabase.ymlwith options supported byRedis.new
development:
redis:
db: 2
production:
redis:
url: 'redis://mymaster'
sentinels:
- host: host
- host: other- You can also provide
pool&timeoutvalues for ConnectionPool. - Use
debug: trueto set redis logger toRails.logger. - Pass
namespaceif you want to use redis-namespace. - Use
Rails.redis_pool&Rails.redismethod.
PooledRedis uses ConnectionPool for pooling connections.
.redis returns proxy object that checkouts connection for every method call.
So you may want to avoid it for bulk operations.
Rails.cache configuration & Redis::Store support
PooledRedis provides configuration of Rails.cache via database.yml.
To enable this add following to your config/application.rb (inside Application class):
PooledRedis.setup_rails_cache(self)And cache sections to database.yml:
development:
cache:
adapter: redis_store
db: 3
expires_in: 3600
production:
cache:
adapter: redis_store
url: 'redis://mycachemaster'
sentinels:
- host: host
- host: other
# You can also use other adapters:
test:
cache:
adapter: null_storeYou need to add gem 'redis-activesupport' to your Gemfile.
It supports only new version of Redis::Store with support of ConnectionPool
(currently it's only available in master:
gem 'redis-activesupport', '~> 4.0.0', github: 'redis-store/redis-activesupport', ref: 'd09ae04').
Custom modules or without rails
- Extend or include
PooledRedismodule. - Override
redis_configmethod to return valid configuration. - Use
redis_pool&redismethods.
class Storage
extend PooledRedis
class << self
def redis_config
read_your_yaml.symbolize_keys
end
end
# ...
def save
self.class.redis.set id, to_json
end
end
Storage.redis_pool.with { |r| r.get :some_key }
Storage.redis.get :some_keyAdvanced usage
You can return hash containing :block from redis_config. This block
will be used as a block to instantiate connection in ConnectionPool.
Licence
MIT