views:

41

answers:

2

I'm using rails 2.3.8 and redis.

In my controllers, each time I want to access redis, I will create a new Redis object, like:

class AbcController < ApplicationController
  def index
     redis => Redis.new
     redis.xxx
  end

  def list
     redis => Redis.new
     redis.xxx
  end
end

I feel this is very bad, and I have some questions here:

  1. Can we create ONE Redis object in somewhere, and we can use it directly anywhere? If yes, how to do it?

  2. Do we need to close(disconnect) the redis object after operation?

+1  A: 

You can instanciate this object in a dedicated initializers like that

RedisConnection = Redis.new

After you can call this Constante in your code.

This object is a Client to Redis. So you can try if allways connected or not by #connected? method. And you can #reconnect it.

shingara
A: 

I wouldn't use a constant for it. Another option is to define this method, probably in config/initializers/redis.rb:

def redis
  Thread.current[:redis] ||= Redis.connect
end

Using Redis.connect allows you to customize the connection URL by using the REDIS_URL environment variable. The basic format is redis://127.0.0.1:6379, but you can do more.

You don't need to worry about connection and disconnection. The client will try to connect the first time it needs to, and if the connection is lost, it will try to reconnect again as needed.

djanowski