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 assigned by Memcach to an already 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 parameters are described as follows:
- **key:** the key in the key-value structure, used to look up the cached value.
- flags: can include an integer parameter of the key-value pair, which the client uses to store extra information about the key-value pair .
- exptime: the length of time to keep the key-value pair in the cache (in seconds, 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 understood directly 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. 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 of a name/value pair.
The example steps are as follows:
- If the unique token is not set, the CAS command executes with an error.
- If the key does not exist, execution fails.
- Add a key-value pair.
- Obtain the unique token via the gets command.
- Use the cas command to update data
- Use the get command to check whether the data was 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, it outputs:
STORED
Description of the output information:
- STORED: output after a successful save.
- ERROR: save error or syntax error.
- EXISTS: another user is also updating the data after the last retrieval.
- NOT_FOUND: the key does not exist on the Memcached service.