通過api:Shiro的Session接口有一個setTimeout()方法
//登錄后,可以用如下方式取得session SecurityUtils.getSubject().getSession().setTimeout(30000);
查看Shiro的api文檔,
setTimeout
void setTimeout(long maxIdleTimeInMillis) throws InvalidSessionExceptionSets the time in milliseconds that the session may remain idle before expiring.A negative value means the session will never expire.A non-negative value (0 or greater) means the session
expiration will occur if idle for that length of time.*Note: if you are used to the HttpSession's getMaxInactiveInterval() method, the scale on this method is different: Shiro Sessions use millisecond values for timeout whereas HttpSession.getMaxInactiveInterval
uses seconds. Always use millisecond values with Shiro sessions.Parameters:maxIdleTimeInMillis - the time in milliseconds that the session may remain idle before expiring.Throws:InvalidSessionException - if the session has been stopped or expired prior to
calling this method.Since:0.2
設置的最大時間,正負都可以,為負數時表示永不超時。開發過程中,設置負數時,遇到點兒問題:
SecurityUtils.getSubject().getSession().setTimeout(-1l);
這樣調用后,總是拋出session已經過時的異常,一直找不到原因,后來調試源碼才發現,這里設置的時間單位是:ms,但是Shiro會把這個時間轉成:s,而且是會舍掉小數部分,這樣我設置的是-1ms,轉成s后就是0s,馬上就過期了,所以后面再對這個會話進行操作時,總會拋異常,正確的設置永不超時的方式應該是:
// timeout:-1000ms 永不超時
SecurityUtils.getSubject().getSession().setTimeout(-1000l);