Created
May 9, 2017 23:20
-
-
Save justinko/1f7519b70b2fcfa96e7af323151abfc3 to your computer and use it in GitHub Desktop.
Distributed Mutex with sidekiq-ent
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
class DistributedMutex | |
Blocked = Class.new(StandardError) | |
DEFAULT_OPTIONS = { | |
wait_timeout: 0, | |
lock_timeout: 30, | |
policy: :raise, | |
ttl: 1.hour | |
} | |
def self.blocking(key, options = {}, &block) | |
new(key, options, &block).blocking | |
end | |
attr_reader :key, :options, :block | |
def initialize(key, options, &block) | |
@options = options.reverse_merge(DEFAULT_OPTIONS) | |
@key, @block = key, block | |
end | |
def blocking | |
blocker.within_limit &block | |
rescue Sidekiq::Limiter::OverLimit | |
raise Blocked, key | |
end | |
private | |
def blocker | |
Sidekiq::Limiter.concurrent( | |
"distributed-mutex-#{key}".parameterize, 1, options | |
) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment