For web applications, cached data can become outdated or irrelevant over time. In these cases, it is necessary to delete specific keys from the Redis cache. This operation is common during updates to database records that are also stored in cache, or when a session expires and related user data needs to be purged from cache.
To handle such scenarios in Go, we typically use the
Example 1: Deleting a single key
In this code piece, we create a connection to a local Redis instance, then delete the key 'key1' from cache.
Example 2: Deleting multiple keys
In this example, we delete multiple keys ('key1', 'key2', 'key3') at once.
Always handle the error returned by
Del() to make sure the operation was successful. If the key doesn't exist, Redis will return 0, not an error, so don't rely solely on error handling to check the existence of a key.
Not checking if a key exists before trying to delete it can lead to confusion: Redis won't throw an error if you try to delete a non-existent key, it just returns 0. Thus, if you want to confirm whether a deletion was successful or if a key was already missing, you need to manually check the key's existence beforehand.
Q: What happens if I try to delete a key that does not exist? A: Redis won't return an error, but rather a zero, indicating no keys were deleted.
Q: Can I delete multiple keys at once?
A: Yes, the
Del() function accepts multiple keys as arguments.