支持定期校验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;
}



