skip to Main Content

In redis i am first storing the key vaue. I’ll check whether the key is present in the subsequent request using GET command for retrieving value. If a key is not accessed for certain duration like 60min then the key should be deleted. otherwise it should be like that only. So, How can we achieve this requirement. I know TTL feature is present in redis but it’ll delete after the specified duration but I wanted the key should be deleted only if it is not accessed for 60min like that.

2

Answers


  1. TTL in redis cannot be set per KEY in the hset, only per whole set
    The reason is that the implementation would be complicated and the creators of redis wanted to keep it as simple as possible.

    Here are some workarounds:

    1. Instead of hset use a top level set/get with TTL/EXPIRE commands
    2. in the value store the expiration time, when you get the value also update the expiration time, issue a delete command from client that gets key/value and discovers that is was supposed to be expired already
    Login or Signup to reply.
  2. If you can save your data as key-value pair, i.e. STRING, instead of HASH. You can achieve the goal with SET command and Lua scripting:

    Set Operation

    When you need to set a key-value pair, also specify a TTL to ensure if there’s no access within 60s, the key will be deleted automatically:

    SET key value EX 60
    

    Get Operation

    When you try to get the value, if the key exists, also reset its TTL to 60s with Lua script:

    -- get.lua
    local key = KEYS[1]
    local val = redis.call("get", key)
    if (val) then
        redis.call("expire", key, 60)
    end
    return val
    

    NOTE: If you don’t want to specify a TTL with the SET command every time, or your Redis version doesn’t support EX option, you can also wrap the SET and EXPIRE commands into a Lua script.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search