Search code examples
spring-bootredishttpsessionspring-data-redisspring-session

How to get session or redis key's expiration time in controller when using Spring's @EnableRedisHttpSession?


I am using Spring Boot and Spring session. Here is my simple config.

@EnableRedisHttpSession
public class Config {}

Spring Boot by default creates a RedisConnectionFactory and I put corresponding host, port information etc in application.yml file(removed for brevity)

I also added security related information(removed it from here for brevity).

Now this is my controller.

@RestController
public HomeController {

    @GetMapping("/hello")
    public String home(HttpSession session){
        // I need redis's key's expiration time. or session id's expiration time. 
        // how can I get this? Should I use HttpSession?
        return "hello";
    }

}

How do I get session expiration time in my controller? or rather how can I get redis's key's expiration time?


Solution

  • You need to use HttpSession

    You can add it as a parameter in your controller method as shown below(also shown in question).

    @GetMapping("/hello")
    public String home(HttpSession session){
        // I need redis's key's expiration time. or session id's expiration time. 
        // how can I get this? Should I use HttpSession?
        int ttl = session.getMaxInactiveInterval(); // this should give redis TTL
        return "hello";
    }
    

    And you can use HttpSession's getMaxInactiveInterval method to get redis's TTL value as shown in the code above.