Home > Database > Redis > body text

How to delete cache in redis

下次还敢
Release: 2024-04-19 23:42:19
Original
1055 people have browsed it

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 cache in redis

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

Notes

  • Be careful with security when deleting cache as this may result in data loss.
  • Use fuzzy delete with caution as it may accidentally delete other keys.
  • Regularly clear caches that are no longer needed to optimize Redis performance.

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template