Memcached CAS Command
The Memcached CAS (Check-And-Set or Compare-And-Swap) command is used to perform a "check and set" operation. It only allows the value to be written if the value associated with the key has not been modified by another client since the last time the current client retrieved it.
The check is performed using the cas_token
parameter, which is a unique 64-bit value assigned by Memcached to an existing element.
Syntax:
The basic syntax format for the CAS command is as follows:
cas key flags exptime bytes unique_cas_token [noreply]
value
Parameter descriptions are as follows:
- key: The key in the key-value structure used to find the cached value.
- flags: An integer parameter that the client can use to store additional information about the key-value pair.
- exptime: The duration for which the key-value pair is stored in the cache (in seconds, 0 means forever).
- bytes: The number of bytes stored in the cache.
- uniquecastoken: A unique 64-bit value obtained through the
gets
command. - noreply (optional): This parameter informs the server not to return data.
- value: The stored value (always on the second line), which can be directly understood as the value in the key-value structure.
Example
To use the CAS command on Memcached, you need to obtain a token from the Memcached service provider via the gets
command.
The gets
command is similar to the basic get
command, but it returns slightly more information: a 64-bit integer value that acts as a "version" identifier for the name/value pair.
Example steps are as follows:
- The CAS command will fail if no unique token is set.
- The operation will fail if the key does not exist.
- Add the key-value pair.
- Obtain the unique token via the
gets
command. - Update the data using the
cas
command. - Check if the data is updated using the
get
command.cas tp 0 900 9 ERROR <− Missing token cas tp 0 900 9 2 memcached NOT_FOUND <− Key tp does not exist 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 will be:
STORED
Output information descriptions are as follows:
- STORED: Output after successful save.
- ERROR: Indicates an error in saving or syntax.
- EXISTS: Another user has updated the data since the last retrieval.
- NOT_FOUND: The key-value does not exist on the Memcached service.