BigW Consortium Gitlab

redis.rb 1.38 KB
Newer Older
1
module Gitlab
2
  class Redis
3
    CACHE_NAMESPACE = 'cache:gitlab'
4 5
    SESSION_NAMESPACE = 'session:gitlab'
    SIDEKIQ_NAMESPACE = 'resque:gitlab'
6

7 8
    attr_reader :url

9 10 11 12 13 14 15
    # To be thread-safe we must be careful when writing the class instance
    # variables @url and @pool. Because @pool depends on @url we need two
    # mutexes to prevent deadlock.
    URL_MUTEX = Mutex.new
    POOL_MUTEX = Mutex.new
    private_constant :URL_MUTEX, :POOL_MUTEX

16
    def self.url
17
      @url || URL_MUTEX.synchronize { @url = new.url }
18 19 20
    end

    def self.with
21 22 23 24 25
      if @pool.nil?
        POOL_MUTEX.synchronize do
          @pool = ConnectionPool.new { ::Redis.new(url: url) }
        end
      end
26
      @pool.with { |redis| yield redis }
27
    end
28

29 30
    def self.redis_store_options
      url = new.url
31
      redis_config_hash = ::Redis::Store::Factory.extract_host_options_from_uri(url)
32 33 34 35 36 37 38 39 40 41 42
      # Redis::Store does not handle Unix sockets well, so let's do it for them
      redis_uri = URI.parse(url)
      if redis_uri.scheme == 'unix'
        redis_config_hash[:path] = redis_uri.path
      end
      redis_config_hash
    end

    def initialize(rails_env=nil)
      rails_env ||= Rails.env
      config_file = File.expand_path('../../../config/resque.yml', __FILE__)
43

44
      @url = "redis://localhost:6379"
45
      if File.exist?(config_file)
46
        @url = YAML.load_file(config_file)[rails_env]
47 48 49
      end
    end
  end
50
end