Spring Shiro基础组件 SessionValidationScheduler

相关阅读

简介

支持定期校验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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值