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 the DEL
command to directly delete the cache of the specified key.
<code>DEL key_name</code>
Batch deletion
Use the KEYS
command to get the keys matching a specific pattern, and then use the UNLINK
command to delete these in batches key.
For example: Delete all keys starting with product_*
:
<code>KEYS product_* UNLINK $(keyspace_keys ...)</code>
Fuzzy delete
Use the SCAN
command to iterate over all keys and use the fnmatch
module in a scripting language such as Python to match keys. Matching keys can be deleted using the UNLINK
command.
Example: Delete all keys containing the string user_ID
:
<code class="python">import redis import fnmatch r = redis.Redis() for key in r.scan_iter(): if fnmatch.fnmatch(key, "*user_ID*"): r.unlink(key)</code>
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 key user_info
to 10 minutes:
<code>EXPIRE user_info 600</code>
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!