There are four methods to delete cache in Redis: direct deletion (DEL command), batch deletion (KEYS UNLINK command), fuzzy deletion (SCAN UNLINK command) and time-based expiration (TTL).
How to delete the cache in Redis
Delete directly
Use theDEL
command to directly delete the cache of the specified key.
DEL key_name
Batch deletion
Use theKEYS
command to get the keys matching a specific pattern, and then use theUNLINK
command to delete these in batches key.
For example: Delete all keys starting withproduct_*
:
KEYS product_* UNLINK $(keyspace_keys ...)
Fuzzy delete
Use theSCAN
command to iterate over all keys and use thefnmatch
module in a scripting language such as Python to match keys. Matching keys can be deleted using theUNLINK
command.
Example: Delete all keys containing the stringuser_ID
:
import redis import fnmatch r = redis.Redis() for key in r.scan_iter(): if fnmatch.fnmatch(key, "*user_ID*"): r.unlink(key)
Time-based expiration (TTL)
If a TTL is set for a key, the key will be automatically deleted upon expiration.
For example: Set the TTL of keyuser_info
to 10 minutes:
EXPIRE user_info 600
Notes
The above is the detailed content of How to delete cache in redis. For more information, please follow other related articles on the PHP Chinese website!