Home> Database> Redis> body text

How to delete cache in redis

下次还敢
Release: 2024-04-19 23:42:19
Original
938 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 theDELcommand to directly delete the cache of the specified key.

DEL key_name
Copy after login

Batch deletion

Use theKEYScommand to get the keys matching a specific pattern, and then use theUNLINKcommand to delete these in batches key.

For example: Delete all keys starting withproduct_*:

KEYS product_* UNLINK $(keyspace_keys ...)
Copy after login

Fuzzy delete

Use theSCANcommand to iterate over all keys and use thefnmatchmodule in a scripting language such as Python to match keys. Matching keys can be deleted using theUNLINKcommand.

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)
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 keyuser_infoto 10 minutes:

EXPIRE user_info 600
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 Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!