Redlock

This library is an implementation of Redlock (Redis destributed lock)

Redlock

Installation

If available in Hex, the package can be installed by adding redlock to your list of dependencies in mix.exs:

def deps do
[
{:redlock, "~> 0.1.0"}
]
end

Documentation can be generated with ExDoc and published on HexDocs. Once published, the docs can be found at https://hexdocs.pm/redlock.

Usage

resource = "example_key:#{user_id}"
lock_exp_sec = 10
case Redlock.lock(resource, lock_exp_sec) do
{:ok, mutex} ->
# some other code which write and read on RDBMS, KVS or other storage
# call unlock finally
Redlock.unlock(resource, mutex)
:error ->
Logger.error "failed to lock resource. maybe redis connection got toruble."
{:error, :system_error}
end

Or you can use transaction function

def my_function() do
# do something, and return {:ok, :my_result} or {:error, :my_error}
end
def execute_with_lock() do
resource = "example_key:#{user_id}"
lock_exp_sec = 10
case Redlock.transaction(resource, lock_exp_sec, &my_function/0) do
{:ok, :my_result} ->
Logger.info "this is the return-value of my_function/0"
:ok
{:error, :my_error} ->
Logger.info "this is the return-value of my_function/0"
:error
{:error, :lock_failure} ->
Logger.info "if locking has failed, Redlock returns this error"
:error
end
end

Setup

children = [
# other workers/supervisors
Redlock.child_spec(redlock_opts)
]
Supervisor.start_link(children, strategy: :one_for_one)

Options

readlock_opts = [
pool_size: 2,
drift_factor: 0.01,
max_retry: 3,
retry_interval: 300,
reconnection_interval: 5_000,
# you must set odd number of server
servers: [
[host: "redis1.example.com", port: 6379],
[host: "redis2.example.com", port: 6379],
[host: "redis3.example.com", port: 6379]
]
]