How to “EXPIRE” the “HSET” child key in redis?

前端 未结 11 2039
予麋鹿
予麋鹿 2020-11-30 21:10

I need to expire all keys in redis hash, which are older than 1 month.

11条回答
  •  离开以前
    2020-11-30 21:29

    You could store key/values in Redis differently to achieve this, by just adding a prefix or namespace to your keys when you store them e.g. "hset_"

    • Get a key/value GET hset_key equals to HGET hset key

    • Add a key/value SET hset_key value equals to HSET hset key

    • Get all keys KEYS hset_* equals to HGETALL hset

    • Get all vals should be done in 2 ops, first get all keys KEYS hset_* then get the value for each key

    • Add a key/value with TTL or expire which is the topic of question:

     SET hset_key value
     EXPIRE hset_key
    

    Note: KEYS will lookup up for matching the key in the whole database which may affect on performance especially if you have big database.

    Note:

    • KEYS will lookup up for matching the key in the whole database which may affect on performance especially if you have big database. while SCAN 0 MATCH hset_* might be better as long as it doesn't block the server but still performance is an issue in case of big database.

    • You may create a new database for storing separately these keys that you want to expire especially if they are small set of keys.

    Thanks to @DanFarrell who highlighted the performance issue related to KEYS

提交回复
热议问题