How to set expiration time for a hash in Redis?
In Redis, the hash data structure itself does not support setting expiration times. However, you can use Redis’s key expiration feature to set an expiration time for the key corresponding to the hash.
The specific steps are as follows:
- Set the expiration time for a hash key using the EXPIRE command. For example, set the expiration time for the hash with the key ‘myhash’ to 60 seconds: EXPIRE myhash 60.
- Before reading a hash, you can use the TTL command to check the remaining expiration time of the key. For example: TTL myhash.
- When the key of a hash expires, the corresponding hash data structure will be automatically deleted.
It is important to note that setting an expiration time is for the entire key of the hash, not for each field within the hash. If you want to set an expiration time for each field in the hash, you can combine hash and sorted set to achieve this.