Read more

Setup Sidekiq and Redis

Klaus Weidinger
October 11, 2021Software engineer at makandra GmbH

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
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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
October 11, 2021Software engineer at makandra GmbH
Posted by Klaus Weidinger to makandra dev (2021-10-11 15:15)