Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Memcached CAS command


May 17, 2021 Memcached



The Check-And-Set or Compare-And-Swap command is used to perform a "check and set" operation

It is only able to write values if the key's corresponding value has not been modified by other clients after the current client's last value.

The check cas_token a unique 64-bit value assigned by Memcach to an existing element.

Grammar:

The basic syntax of the CAS command is as follows:

cas key flags exptime bytes unique_cas_token [noreply]
value

The parameters are described below:

  • Key: Key in the key-value structure to find cached values.
  • flags: You can include integer parameters for key value pairs, which the client uses to store additional information about key value pairs.
  • exptime: The length of time (in seconds, 0 means forever) to save key pairs in the cache
  • Bytes: The number of bytes stored in the cache
  • unique_cas_token a unique 64-bit value obtained by the gets command.
  • Noreply (optional): This parameter tells the server that no data needs to be returned
  • value: Stored value (always on the second row) (can be understood directly as value in key-value structure)

Instance

To use CAS commands on Memcached, you need to obtain a token (token) from the Memcached service provider through the gets command.

The gets command functions like a basic get command. T he difference between the two commands is that gets returns slightly more information: the 64-bit integer value is very much like the "version" identifier of a name/value pair.

The example steps are as follows:

  • If a unique token is not set, the CAS command executes incorrectly.
  • If the key key does not exist, execution fails.
  • Add a key value pair.
  • Get a unique token with the gets command.
  • Update the data with the cas command
  • Use the get command to see if the data is updated
cas tp 0 900 9
ERROR             <− 缺少 token

cas tp 0 900 9 2
memcached
NOT_FOUND         <−  tp 不存在

set tp 0 900 9
memcached
STORED

gets tp
VALUE tp 0 9 1
memcached
END

cas tp 0 900 5 1
redis
STORED

get tp
VALUE tp 0 5
redis
END

Output

If the data is added successfully, the output:

STORED

Output information description:

  • STORED: The output after the successful save.
  • ERROR: Save error or syntax error.
  • EXISTS: Another user is also updating the data after the last value.
  • NOT_FOUND: The key value does not exist on the Memcached service.