Setup Sidekiq and Redis

Updated . Posted . Visible to the public.

If you want Sidekiq to be able to talk to Redis on staging and production servers, you need to add the following to your configuration:

# config/initializers/sidekiq.rb
require 'sidekiq'

Sidekiq.configure_client do |config|
  config.redis = { url: REDIS_URL }
end

Sidekiq.configure_server do |config|
  config.redis = { url: REDIS_URL }
end

The following step may be skipped for new Sidekiq 6+, since it isn't recommended anymore to use a global redis client.

# config/initializers/redis.rb
require 'redis'
require_relative '../constants/redis'

Redis.current = Redis.new(url: REDIS_URL)

Redis.current deprecated

Version 4.6 introduces deprecation warning for Redis.current, which will be removed altogether in 5.0. Read this card for ways to deal with this.

Now we can determine the correct REDIS_URL like this:

# config/constants/redis.rb
module RedisConstantHelper
  module_function

  def redis_url
    "redis://localhost:#{port}/#{db_number}"
  end

  def db_number
    # Returns a number between 2 and n.
    # Redis db#1 is used for development.

    db_number = 1

    if rails_env == 'test'
      normalized_test_number = [ENV['TEST_ENV_NUMBER'].to_i, 1].max
      db_number += normalized_test_number
    end

    db_number
  end

  def port
    case rails_env
    when 'staging'
      # <staging_port>
    when 'production'
      # <production_port>
    else
      6379 # default Redis port
    end
  end

  def rails_env
    defined?(Rails) ? Rails.env : ENV['RAILS_ENV']
  end
end

REDIS_URL = RedisConstantHelper.redis_url

Make sure to require the /constants folder on startup:

# config/application.rb
module ProjectName
  class Application < Rails::Application
    
    # require /constants on startup
    Dir.glob(Rails.root.join('config/constants/**/*.rb')).each do |filename|
      require filename
    end
    
  end
end
Klaus Weidinger
Last edit
Felix Eschey
License
Source code in this card is licensed under the MIT License.
Posted by Klaus Weidinger to makandra dev (2021-10-11 13:15)