w3resource

Redis String: Getset

Redis GETSET Command

Redis GETSET command automatically set specified string value in redis key and returns its old value. Returns an error when key exists but does not hold a string value.

Here are some common uses and scenarios for the "GETSET" command:

  • Atomic Swap: Atomically replace a key's value and retrieve the old value.
  • Counters and Flags: Update counters or flags while getting their previous state.
  • Session Handling: Update session tokens or identifiers and retrieve the previous ones.
  • Optimistic Locking: Implement optimistic locking by setting a new value and checking the old one.
  • Data Migration: Move or update data while preserving the previous value for verification.<./
  • Syntax:

    GETSET KEY_NAME VALUE
    

    Available since

    1.0.0.

    Return Value

    Simple string reply, the old value of a key. If the key does not exist, then nil is returned.

    Return Value Type

    String

    Example: Redis GETSET

    redis 127.0.0.1:6379> GETSET mynewkey "This is my test key"
    (nil)
    redis 127.0.0.1:6379> GETSET mynewkey "This is my new value to test getset"
    "This is my test key"
    

    Previous: GETRANGE
    Next: GETBIT



Follow us on Facebook and Twitter for latest update.