Memcached CAS Command
The Memcached CAS (Check-And-Set or Compare-And-Swap) command is used to perform a "check and set" operation.
It can only write the value if, after the current client last retrieved the value, the value corresponding to the key has not been modified by other clients.
The check is performed through the cas_token parameter, which is a unique 64-bit value that Memcached assigns to an existing element.
Syntax:
The basic syntax format of the CAS command is as follows:
cas key flags exptime bytes unique_cas_token [noreply] value
The parameter descriptions are as follows:
- key:The key in the key-value structure, used to look up the cached value.
- flags: An integer parameter that can include key-value pairs; the client uses it to store additional information about the key-value pair.
- exptime: The length of time (in seconds) to store the key-value pair in the cache (0 means forever)
- bytes: The number of bytes stored in the cache
- unique_cas_tokenA unique 64-bit value obtained through the gets command.
- noreply (optional): This parameter tells the server that it does not need to return data
- value: The stored value (always on the second line) (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 server using the gets command.
The gets command functions similarly to the basic get command. The difference between the two commands is that gets returns slightly more information: a 64-bit integer value that is very much like a "version" identifier for the name/value pair.
The example steps are as follows:
- If no unique token is set, the CAS command will return an error.
- If the key does not exist, the execution fails.
- Add a key-value pair.
- Obtain a unique token through the gets command.
- Use the cas command to update the data
- Use the get command to check whether the data has been 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 is:
STORED
Description of the output information:
- STORED: Output after a successful save.
- ERROR: Save error or syntax error.
- EXISTS: Another user also updated the data after the last retrieval.
- NOT_FOUND: The key-value pair does not exist on the Memcached server.