相关阅读
- Spring Shiro基础组件 Session
- Spring Shiro基础组件 SessionDao
- Spring Shiro基础组件 SessionFactory
- Spring Shiro基础组件 SessionKey
- Spring Shiro基础组件 SessionManager
简介
支持定期校验Session
,由DefaultSessionManager
调用实现Session
校验;
核心方法
/**
* 是否启用
*/
boolean isEnabled();
/**
* 启用校验
*/
void enableSessionValidation();
/**
* 禁用校验
*/
void disableSessionValidation();
实现子类
public interface SessionValidationScheduler
public class ExecutorServiceSessionValidationScheduler implements SessionValidationScheduler, Runnable
ExecutorServiceSessionValidationScheduler
简介
借助ScheduledExecutorService
实现定期校验Session
;
###核心方法
// Session管理器
ValidatingSessionManager sessionManager;
// 策略执行服务
private ScheduledExecutorService service;
// 间隔时长
private long interval = DefaultSessionManager.DEFAULT_SESSION_VALIDATION_INTERVAL;
// 启用标识
private boolean enabled = false;
// 线程名称前缀
private String threadNamePrefix = "SessionValidationThread-";
/**
* 是否启用
*/
public boolean isEnabled() {
return this.enabled;
}
/**
* 启用校验
*/
public void enableSessionValidation() {
if (this.interval > 0l) {
// 创建单线程池
this.service = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
private final AtomicInteger count = new AtomicInteger(1);
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
// 设置后台运行
thread.setDaemon(true);
// 设置线程名称
thread.setName(threadNamePrefix + count.getAndIncrement());
return thread;
}
});
// 启动线程池
this.service.scheduleAtFixedRate(this, interval, interval, TimeUnit.MILLISECONDS);
}
// 设置启用标识
this.enabled = true;
}
/**
* 线程运行任务
*/
public void run() {
if (log.isDebugEnabled()) {
log.debug("Executing session validation...");
}
Thread.currentThread().setUncaughtExceptionHandler((t, e) -> {
log.error("Error while validating the session, the thread will be stopped and session validation disabled", e);
// 禁用校验
this.disableSessionValidation();
});
long startTime = System.currentTimeMillis();
try {
// 校验Session
this.sessionManager.validateSessions();
} catch (RuntimeException e) {
log.error("Error while validating the session", e);
//we don't stop the thread
}
long stopTime = System.currentTimeMillis();
if (log.isDebugEnabled()) {
log.debug("Session validation completed successfully in " + (stopTime - startTime) + " milliseconds.");
}
}
/**
* 禁用校验
*/
public void disableSessionValidation() {
if (this.service != null) {
this.service.shutdownNow();
}
this.enabled = false;
}