-
-
Notifications
You must be signed in to change notification settings - Fork 73
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Make Redis an optional dependency. Handle URL resolution gracefully i…
…f Redis is unavailable.
- Loading branch information
1 parent
a122fb2
commit e6ee86f
Showing
4 changed files
with
49 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,46 @@ | ||
# frozen_string_literal: true | ||
|
||
begin | ||
$redis = Redis.new | ||
rescue | ||
puts "Failed to connect to redis!" | ||
# Monkeypatch redis to throttle it from attempting to connect more often than once a second | ||
|
||
class Redis | ||
class ThrottledConnectError < BaseConnectionError | ||
end | ||
|
||
class Client | ||
@@last_connect_error = nil | ||
|
||
# https://github.com/redis/redis-rb/blob/v4.6.0/lib/redis/client.rb#L379-L399 | ||
def establish_connection | ||
if @@last_connect_error && Time.now < @@last_connect_error + 1 | ||
raise ThrottledConnectError, "Throttled connection attempt to Redis on #{location}" | ||
end | ||
|
||
server = @connector.resolve.dup | ||
|
||
@options[:host] = server[:host] | ||
@options[:port] = Integer(server[:port]) if server.include?(:port) | ||
|
||
@connection = @options[:driver].connect(@options) | ||
@pending_reads = 0 | ||
rescue TimeoutError, | ||
SocketError, | ||
Errno::EADDRNOTAVAIL, | ||
Errno::ECONNREFUSED, | ||
Errno::EHOSTDOWN, | ||
Errno::EHOSTUNREACH, | ||
Errno::ENETUNREACH, | ||
Errno::ENOENT, | ||
Errno::ETIMEDOUT, | ||
Errno::EINVAL => error | ||
|
||
@@last_connect_error = Time.now | ||
raise CannotConnectError, "Error connecting to Redis on #{location} (#{error.class})" | ||
end | ||
end | ||
end | ||
|
||
if ENV.has_key?("REDIS_URL") | ||
$redis = Redis.new({ | ||
reconnect_attempts: 0, | ||
}) | ||
end |