SET
SET
We can set a string value to a key using the set command.
SET mykey 'my value'
>>> OK
In order to check if the value was stored correctly, we can use the get command.
GET mykey
>>> "my value"
In the example above, the key mykey was created with the value my value.
If the key already exists, the set command can be used to change the key’s value.
SET mykey 'my changed value'
>>> OK
GET mykey
>>> "my changed value"
SET NX
The NX parameter will only set a key if it does not already exist in Redis.
Still using the examples above, I will attempt to change the value of the key mykey, which is currently my changed key, to new value using the NX parameter.
SET mykey 'new value' NX
>>> (nil)
Since the key mykey already existed, the key’s value was not changed.
GET mykey
>>> "my changed value"
SET XX
The set command with the XX parameter only sets the value of a key if that key already exists.
SET mykey 'new value' XX
>>> OK
GET mykey
>>> "new value"
SET EX
The EX parameter sets the expiration time for the key in seconds within Redis.
SET expkey 'my value' EX 10
>>> OK
The above command sets the key expkey with the value my value and specifies that the key should only last for 10 seconds.
If you try to retrieve the value of the key after 10 seconds, nil will be returned.
GET expkey
>>> "my value"
DEL
When it is necessary to remove a key, the DEL command can be used.
SET mykey 'new value'
>>> OK
GET mykey
>>> "my value"
DEL mykey
>>> (integer) 1
SET EXAT
The above command sets the key expkey with the value my value using the EXAT parameter, specifying that the key should last only until the specified time in Unix epoch time format, in seconds.
SET expkey 'my value' EXAT 1765219320
>>> OK
SET PXAT
The above command sets the key expkey with the value my value using the PXAT parameter, specifying that the key should last only until the specified time in Unix epoch time format, in milliseconds.
SET expkey 'my value' PXAT 1765219320000
>>> OK
SET KEEPTTL
The above command sets the key expkey with the value my new value while respecting the TTL that was defined using the set command with the EX parameter. Example:
SET expkey 'my old value' EX 60
>>> OK
SET expkey 'my new value' KEEPTTL
>>> OK
The value will be my new value while respecting the TTL of 60 seconds, which will be preserved.