redis_mutex v0.2.0 RedisMutex.Lock View Source

This module contains the actual Redis locking business logic. The with_lock macro is generally the only function that should be used from this module, as it will handle the logic for setting and removing key/values in Redis.

Link to this section Summary

Functions

This function takes in a key and a unique identifier to set it in Redis. This is how a lock is identified in Redis. If a key/value pair is able to be set in Redis, lock returns true. If it isn't able to set in Redis, lock returns false.

This function takes in a key, unique string, and a timeout in milliseconds. It will call itself recursively until it is able to set a lock or the timeout expires.

This function takes in the key/value pair that are to be released in Redis

This macro takes in a key and a timeout.

Link to this section Functions

This function takes in a key and a unique identifier to set it in Redis. This is how a lock is identified in Redis. If a key/value pair is able to be set in Redis, lock returns true. If it isn't able to set in Redis, lock returns false.

Link to this function

take_lock(key, uuid, timeout \\ 40000, start \\ nil, finish \\ nil) View Source

This function takes in a key, unique string, and a timeout in milliseconds. It will call itself recursively until it is able to set a lock or the timeout expires.

This function takes in the key/value pair that are to be released in Redis

Link to this function

unlock_script(client, keys \\ [], argv \\ []) View Source

Link to this macro

with_lock(key, timeout \\ 40000, list) View Source (macro)

This macro takes in a key and a timeout.

A key might be be an id or a resource identifier that will lock a particular resource. A good example might be an email or phone number for a user, and you might want lock a db insert so that multiple users aren't created for one email or phone number.

The timeout is in milliseconds and defaults to 40000 milliseconds. There is a key expiration of 20 seconds, so the timeout should always be greater than 20 seconds. The 20 second expiry allows the key to expire in case the logic inside the with_lock macro throws an error or fails to complete within 20 seconds, thereby freeing up the key so the lock can be obtained by another request or resource.

The lock will be released after the logic inside the with_lock has completed, or the timeout, whichever comes first. The return value of the macro will be the return value of the logic inside the 'with_lock' macro.

  defmodule PossumLodge do
    use RedisMutex
    alias PossumLodge.{Repo, Member}

    def add_member(params) do
      with_lock(params.phone_number) do
        %Member{}
        |> Member.changeset(params)
        |> Repo.insert_or_update!
      end
    end
  end