简体   繁体   中英

Is Redis connection shared in Rails?

In my Rails app I have an initializer that creates a Redis connection:

$redis = Redis.new(:host => 'localhost', :port => 6379, :db => 3)

My question is: is this connection shared for all workers for this app, or does each worker thread create its own connection everytime I use $redis?

You can try using gem connection_pool , which is generic pool for any network client.

Gemfile:

gem 'connection_pool'

initializers/redis.rb:

require 'connection_pool'

conf = YAML.load(File.read(File.join('config','redis.yml')))
redis_config = conf[Rails.env.to_s]

Redis.current = ConnectionPool.new(size: 10, timeout: 5) do 
  Redis.new host: redis_config['host'], port: redis_config['port'], db: redis_config['db']
end

config/redis.yml

development:
  host: localhost
  port: 6379
  db: 0
test:
  host: localhost
  port: 6379
  db: 15
production:
  host: localhost
  port: 6379
  db: 0

Then later, in your code:

Redis.current.with do |conn|
  value = conn.get('foo')
  conn.sadd('bar', 1)
end

Inside the with block, conn will contains a Redis object from the pool. It will be returned to the pool when the block exits, either normally or because an exception was thrown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM