123456789_123456789_123456789_123456789_123456789_

Module: Redis::Commands::Transactions

Relationships & Source Files
Extension / Inclusion / Inheritance Descendants
Included In:
Defined in: lib/redis/commands/transactions.rb

Instance Method Summary

Instance Method Details

#discardString

Discard all commands issued after MULTI.

Returns:

  • (String)

    "OK"

See Also:

[ GitHub ]

  
# File 'lib/redis/commands/transactions.rb', line 110

def discard
  send_command([:discard])
end

#execnil, Array<...>

Execute all commands issued after MULTI.

Only call this method when #multi was called without a block.

Returns:

  • (nil, Array<...>)
    • when commands were not executed, nil
    • when commands were executed, an array with their replies

See Also:

[ GitHub ]

  
# File 'lib/redis/commands/transactions.rb', line 100

def exec
  send_command([:exec])
end

#multi {|multi| ... } ⇒ Array<...>

Mark the start of a transaction block.

Examples:

With a block

redis.multi do |multi|
  multi.set("key", "value")
  multi.incr("counter")
end # => ["OK", 6]

Yields:

  • (multi)

    the commands that are called inside this block are cached and written to the server upon returning from it

Yield Parameters:

Returns:

  • (Array<...>)
    • an array with replies

See Also:

[ GitHub ]

  
# File 'lib/redis/commands/transactions.rb', line 23

def multi
  synchronize do |client|
    client.multi do |raw_transaction|
      yield MultiConnection.new(raw_transaction)
    end
  end
end

#unwatchString

Forget about all watched keys.

Returns:

  • (String)

    OK

See Also:

[ GitHub ]

  
# File 'lib/redis/commands/transactions.rb', line 86

def unwatch
  send_command([:unwatch])
end

#watch(*keys) ⇒ Object, String

Watch the given keys to determine execution of the MULTI/EXEC block.

Using a block is optional, but is necessary for thread-safety.

An #unwatch is automatically issued if an exception is raised within the block that is a subclass of StandardError and is not a ::Redis::ConnectionError.

Examples:

With a block

redis.watch("key") do
  if redis.get("key") == "some value"
    redis.multi do |multi|
      multi.set("key", "other value")
      multi.incr("counter")
    end
  else
    redis.unwatch
  end
end
  # => ["OK", 6]

Without a block

redis.watch("key")
  # => "OK"

Parameters:

  • keys (String, Array<String>)

    one or more keys to watch

Returns:

  • (Object)

    if using a block, returns the return value of the block

  • (String)

    if not using a block, returns OK

See Also:

[ GitHub ]

  
# File 'lib/redis/commands/transactions.rb', line 61

def watch(*keys)
  synchronize do |client|
    res = client.call_v([:watch] + keys)

    if block_given?
      begin
        yield(self)
      rescue ConnectionError
        raise
      rescue StandardError
        unwatch
        raise
      end
    else
      res
    end
  end
end