Skip to content

Commit

Permalink
Utilize a monitor when using the client.
Browse files Browse the repository at this point in the history
`RedisClient` is not thread safe. Thus we should do what `redis-rb`
does and use a `Monitor` when calling the `client`.
  • Loading branch information
dhruvCW committed Aug 19, 2023
1 parent be5d206 commit 423da9f
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions lib/redlock/client.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
require 'monitor'
require 'redis-client'
require 'securerandom'

Expand Down Expand Up @@ -163,6 +164,8 @@ def with
end

def initialize(connection)
@monitor = Monitor.new

if connection.respond_to?(:with)
@redis = connection
else
Expand Down Expand Up @@ -198,17 +201,21 @@ def initialize_client(options)
end
end

def synchronize
@monitor.synchronize { @redis.with { |connection| yield(connection) } }
end

def lock(resource, val, ttl, allow_new_lock)
recover_from_script_flush do
@redis.with { |conn|
synchronize { |conn|
conn.call('EVALSHA', Scripts::LOCK_SCRIPT_SHA, 1, resource, val, ttl, allow_new_lock)
}
end
end

def unlock(resource, val)
recover_from_script_flush do
@redis.with { |conn|
synchronize { |conn|
conn.call('EVALSHA', Scripts::UNLOCK_SCRIPT_SHA, 1, resource, val)
}
end
Expand All @@ -218,7 +225,7 @@ def unlock(resource, val)

def get_remaining_ttl(resource)
recover_from_script_flush do
@redis.with { |conn|
synchronize { |conn|
conn.call('EVALSHA', Scripts::PTTL_SCRIPT_SHA, 1, resource)
}
end
Expand All @@ -235,7 +242,7 @@ def load_scripts
Scripts::PTTL_SCRIPT
]

@redis.with do |connnection|
synchronize do |connnection|
scripts.each do |script|
connnection.call('SCRIPT', 'LOAD', script)
end
Expand Down

0 comments on commit 423da9f

Please sign in to comment.