Max Rose-Collins
Max Rose-Collins

Reputation: 1924

Ruby on Rails - Puma on_worker_boot connect with redis

I'm trying to connect with redis on heroku using Puma but I keep running into the error

Read error: #<Redis::CannotConnectError: Error connecting to Redis on 127.0.0.1:6379 (Errno::ECONNREFUSED)>

I've searched stackoverflow but none of the answers seem to fix my issue.

My puma.rb config

workers Integer(ENV['WEB_CONCURRENCY'] || 2)
threads_count = Integer(ENV['MAX_THREADS'] || 5)
threads threads_count, threads_count

preload_app!

rackup      DefaultRackup
port        ENV['PORT']     || 3000
environment ENV['RACK_ENV'] || 'development'

on_worker_boot do
  ActiveRecord::Base.establish_connection

  Redis.current.client.reconnect
  $redis = Redis.current
end

My redis.rb initializer

$redis = Redis.new(:url => ENV["REDISCLOUD_URL"])

I checked ENV["REDISCLOUD_URL"] that is redis://rediscloud:[email protected]:port

I can't figure out what I am doing wrong, it all seems correct to me

Upvotes: 2

Views: 3267

Answers (1)

Max Rose-Collins
Max Rose-Collins

Reputation: 1924

I had to set config var heroku config:set REDIS_PROVIDER=REDISCLOUD_URL

Puma.rb

workers Integer(ENV['WEB_CONCURRENCY'] || 2)
threads_count = Integer(ENV['MAX_THREADS'] || 5)
threads threads_count, threads_count

preload_app!

rackup      DefaultRackup
port        ENV['PORT']     || 3000
environment ENV['RACK_ENV'] || 'development'

on_worker_boot do
  ActiveRecord::Base.establish_connection

  if ENV["REDISCLOUD_URL"]
    uri = URI.parse(ENV["REDISCLOUD_URL"])
    Redis.current = Redis.new(host: uri.host, port: uri.port, password: uri.password)
    $redis = Redis.current
  else
    Redis.current.quit
  end
end

redis.rb

if ENV["REDISCLOUD_URL"]
  uri = URI.parse(ENV["REDISCLOUD_URL"])
  $redis = Redis.new(host: uri.host, port: uri.port, password: uri.password)
end

Upvotes: 5

Related Questions