skip to Main Content

I have class which I am using to use in redis with some TTL associated with every object. Many time some of the object needed to be access beyond ttl, In other words we want the ttl timer to be reset if the object is access recently.

@Data 
@RedisHash("CodeTokenMap") 
public class CodeTokenMap {
    @Id 
    String aCode;
    String acsToken;
    @TimeToLive private Long ttl;

}

So X object has ttl=30sec, the object is recently accessed at 28sec this ttl countdown should be resetted.

2

Answers


  1. We can have a field in this class for the last accessed time which we can update every time the object is accessed. Thn we can have a method that calculates the time since the last access and compares it with the TTL value. If within the TTL it can return true. A PseudoCode:

    @TimeToLive private Long ttl;
    private Long lastAccessed;
    
        // method to update this field
        void updateLastAccessed() {
            lastAccessed = System.currentTimeMillis();
        }
    
        // Has this obj been used within TTL?
        public boolean isUsedRecent() {
            if (lastAccessed == null)
                return false;
            
            long currentTime = System.currentTimeMillis();
            long timeSinceLastUse = currentTime - lastAccessed;
            return timeSinceLastUse <= ttl * 1000;
        }
    
    

    These methods can be called when the objects are accessed and update the ttl accordingly.

    Login or Signup to reply.
  2. Reading access doesn’t change the TTL of Redis object, only writing access.

    Solution

    Implement a service method like this:

    public String getAndResetToken(String code) {
        CodeTokenMap map = tokenRepository.getById(code);
        map.setTtl(30);
        map = tokenRepository.save(map);
        return map.getAcsToken();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search