最近項目遇到問題,shiro框異常退出沒有清除緩存信息,服務器重啓後,又拿舊的緩存session來登錄,造成後臺報錯。
這裏轉載網友的文章,記錄一下解決方法。大體就是重寫sessionManager類,做一個清除操作。
配置默認會話管理器:
<bean id="sessionManager" class="com.xzjc.common.security.SimpleWebSessionManager">
<property name="globalSessionTimeout" value="15000" />
<property name="sessionValidationInterval" value="30000" />
<property name="sessionValidationSchedulerEnabled" value="true" />
</bean>
全局的會話信息設置成15秒,檢測掃描信息間隔30秒,第三個參數就是是否開啓掃描
重寫管理器類的一個方法
package com.xzjc.common.security;
import java.util.Collection;
import java.util.Iterator;
import org.apache.log4j.Logger;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.ExpiredSessionException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
/**
* 會話管理器,重寫
* @author zhouyujie
*/
public class SimpleWebSessionManager extends DefaultWebSessionManager {
private CacheManager cacheManager;
private final static Logger logger = Logger.getLogger(SimpleWebSessionManager.class);
public SimpleWebSessionManager() {
super();
}
public void validateSessions() {
if (logger.isInfoEnabled()){
logger.info("Validating all active sessions...");
}
int invalidCount = 0;
Collection<?> activeSessions = getActiveSessions();
if (activeSessions != null && !activeSessions.isEmpty()) {
for (Iterator<?> i$ = activeSessions.iterator(); i$.hasNext();) {
Session session = (Session) i$.next();
try {
SessionKey key = new DefaultSessionKey(session.getId());
validate(session, key);
} catch (InvalidSessionException e) {
if (cacheManager != null) {
SimpleSession s = (SimpleSession) session;
if (s.getAttribute("portal.session.id") != null){
cacheManager.getCache(null).remove(s.getAttribute("portal.session.id"));
}
}
if (logger.isDebugEnabled()) {
boolean expired = e instanceof ExpiredSessionException;
String msg = (new StringBuilder()).append("Invalidated session with id [").append(session.getId()).append("]").append(expired ? " (expired)" : " (stopped)").toString();
logger.debug(msg);
}
invalidCount++;
}
}
}
if (logger.isInfoEnabled()) {
String msg = "Finished session validation.";
if (invalidCount > 0){
msg = (new StringBuilder()).append(msg).append("[").append(invalidCount).append("] sessions were stopped.").toString();
}else{
msg = (new StringBuilder()).append(msg).append("No sessions were stopped.").toString();
}
logger.info(msg);
}
}
public void setCacheManager(CacheManager cacheManager) {
this.cacheManager = cacheManager;
}
}
這樣就好使了。