Nebulex.Adapter.Transaction behaviour (Nebulex v3.0.0-rc.1)
View SourceSpecifies the adapter Transaction API.
Default implementation
This module also provides a default implementation which uses the Erlang
library :global
.
This implementation accepts the following options:
:keys
(list ofterm/0
) - The list of keys the transaction will lock. Since the lock ID is generated based on the key, the transaction uses a fixed lock ID if the option is not provided or is an empty list. Then, all subsequent transactions without this option (or set to an empty list) are serialized, and performance is significantly affected. For that reason, it is recommended to pass the list of keys involved in the transaction. The default value is[]
.:nodes
(list ofatom/0
) - The list of the nodes where to set the lock.The default value is
[node()]
.:retries
(:infinity
|non_neg_integer/0
) - If the key has already been locked by another process and retries are not equal to 0, the process sleeps for a while and tries to execute the action later. When:retries
attempts have been made, an exception is raised. If:retries
is:infinity
(the default), the function will eventually be executed (unless the lock is never released). The default value is:infinity
.
Let's see an example:
MyCache.transaction fn ->
counter = MyCache.get(:counter)
MyCache.set(:counter, counter + 1)
end
Locking only the involved key (recommended):
MyCache.transaction(
fn ->
counter = MyCache.get(:counter)
MyCache.set(:counter, counter + 1)
end,
[keys: [:counter]]
)
MyCache.transaction(
fn ->
alice = MyCache.get(:alice)
bob = MyCache.get(:bob)
MyCache.set(:alice, %{alice | balance: alice.balance + 100})
MyCache.set(:bob, %{bob | balance: bob.balance + 100})
end,
[keys: [:alice, :bob]]
)
Summary
Callbacks
Returns {:ok, true}
if the current process is inside a transaction;
otherwise, {:ok, false}
is returned.
Runs the given function inside a transaction.
Callbacks
@callback in_transaction?(Nebulex.Adapter.adapter_meta(), Nebulex.Cache.opts()) :: Nebulex.Cache.ok_error_tuple(boolean())
Returns {:ok, true}
if the current process is inside a transaction;
otherwise, {:ok, false}
is returned.
If there's an error with executing the command, {:error, reason}
is returned, where reason
is the cause of the error.
@callback transaction(Nebulex.Adapter.adapter_meta(), fun(), Nebulex.Cache.opts()) :: Nebulex.Cache.ok_error_tuple(any())
Runs the given function inside a transaction.
If an Elixir exception occurs, the exception will bubble up from the
transaction function. If the cache aborts the transaction, it returns
{:error, reason}
.
A successful transaction returns the value returned by the function wrapped
in a tuple as {:ok, value}
.