• 修改build.gradle
 
compile ("org.quartz-scheduler:quartz:2.2.3")
compile ("org.apache.shiro:shiro-quartz:${shiro}") {
    exclude group: "org.opensymphony.quartz"
}
  • 编写java类
 
package org.apache.shiro.session.mgt.quartz;
 
/**
* Created by koko on 2016/7/20.
*/
import org.apache.shiro.session.mgt.ValidatingSessionManager;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
/**
* 基于Quartz 2.* 版本的实现
*
*/
public class QuartzSessionValidationJob2 implements Job {
 
    /**
    * Key used to store the session manager in the job data map for this job.
    */
    public static final String SESSION_MANAGER_KEY = "sessionManager";
 
    /*--------------------------------------------
    |    I N S T A N C E  V A R I A B L E S    |
    ============================================*/
    private static final Logger log = LoggerFactory.getLogger(QuartzSessionValidationJob2.class);
 
    /*--------------------------------------------
    |        C O N S T R U C T O R S          |
    ============================================*/
 
    /*--------------------------------------------
    |  A C C E S S O R S / M O D I F I E R S    |
    ============================================*/
 
    /*--------------------------------------------
    |              M E T H O D S              |
    ============================================*/
 
    /**
    * Called when the job is executed by quartz. This method delegates to the <tt>validateSessions()</tt> method on the
    * associated session manager.
    *
    * @param context
    *            the Quartz job execution context for this execution.
    */
    public void execute(JobExecutionContext context) throws JobExecutionException {
 
        JobDataMap jobDataMap = context.getMergedJobDataMap();
        ValidatingSessionManager sessionManager = (ValidatingSessionManager) jobDataMap.get(SESSION_MANAGER_KEY);
 
        if (log.isDebugEnabled()) {
            log.debug("Executing session validation Quartz job...");
        }
 
        sessionManager.validateSessions();
 
        if (log.isDebugEnabled()) {
            log.debug("Session validation Quartz job complete.");
        }
    }
 
}

 
 
package org.apache.shiro.session.mgt.quartz;
 
/**
* Created by koko on 2016/7/20.
*/
import org.apache.shiro.session.mgt.DefaultSessionManager;
import org.apache.shiro.session.mgt.SessionValidationScheduler;
import org.apache.shiro.session.mgt.ValidatingSessionManager;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
/**
* 基于Quartz 2.* 版本的实现
*/
public class QuartzSessionValidationScheduler2 implements SessionValidationScheduler {
 
    public static final long DEFAULT_SESSION_VALIDATION_INTERVAL = DefaultSessionManager.DEFAULT_SESSION_VALIDATION_INTERVAL;
    private static final String JOB_NAME = "SessionValidationJob";
    private static final Logger log = LoggerFactory.getLogger(QuartzSessionValidationScheduler2.class);
    private static final String SESSION_MANAGER_KEY = QuartzSessionValidationJob2.SESSION_MANAGER_KEY;
    private Scheduler scheduler;
    private boolean schedulerImplicitlyCreated = false;
 
    private boolean enabled = false;
    private ValidatingSessionManager sessionManager;
    private long sessionValidationInterval = DEFAULT_SESSION_VALIDATION_INTERVAL;
 
    public QuartzSessionValidationScheduler2() {
    }
 
    public QuartzSessionValidationScheduler2(ValidatingSessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }
 
    protected Scheduler getScheduler() throws SchedulerException {
        if (this.scheduler == null) {
            this.scheduler = StdSchedulerFactory.getDefaultScheduler();
            this.schedulerImplicitlyCreated = true;
        }
        return this.scheduler;
    }
 
    public void setScheduler(Scheduler scheduler) {
        this.scheduler = scheduler;
    }
 
    public void setSessionManager(ValidatingSessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }
 
    public boolean isEnabled() {
        return this.enabled;
    }
 
    public void setSessionValidationInterval(long sessionValidationInterval) {
        this.sessionValidationInterval = sessionValidationInterval;
    }
 
    public void enableSessionValidation() {
        if (log.isDebugEnabled()) {
            log.debug("Scheduling session validation job using Quartz with session validation interval of ["
                    + this.sessionValidationInterval + "]ms...");
        }
 
        try {
            SimpleTrigger trigger = TriggerBuilder.newTrigger().startNow().withIdentity(JOB_NAME, Scheduler.DEFAULT_GROUP)
                    .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInMilliseconds(sessionValidationInterval))
                    .build();//<span style="color:#ff0000;">Quartz 2中的实现</span>
 
            JobDetail detail = JobBuilder.newJob(QuartzSessionValidationJob2.class)
                    .withIdentity(JOB_NAME, Scheduler.DEFAULT_GROUP).build();
            detail.getJobDataMap().put(SESSION_MANAGER_KEY, this.sessionManager);
            Scheduler scheduler = getScheduler();
 
            scheduler.scheduleJob(detail, trigger);
            if (this.schedulerImplicitlyCreated) {
                scheduler.start();
                if (log.isDebugEnabled()) {
                    log.debug("Successfully started implicitly created Quartz Scheduler instance.");
                }
            }
            this.enabled = true;
 
            if (log.isDebugEnabled())
                log.debug("Session validation job successfully scheduled with Quartz.");
        } catch (SchedulerException e) {
            if (log.isErrorEnabled())
                log.error("Error starting the Quartz session validation job.  Session validation may not occur.", e);
        }
    }
 
    public void disableSessionValidation() {
        if (log.isDebugEnabled()) {
            log.debug("Stopping Quartz session validation job...");
        }
        Scheduler scheduler;
        try {
            scheduler = getScheduler();
            if (scheduler == null) {
                if (log.isWarnEnabled()) {
                    log.warn("getScheduler() method returned a null Quartz scheduler, which is unexpected.  Please check your configuration and/or implementation.  Returning quietly since there is no validation job to remove (scheduler does not exist).");
                }
 
                return;
            }
        } catch (SchedulerException e) {
            if (log.isWarnEnabled()) {
                log.warn("Unable to acquire Quartz Scheduler.  Ignoring and returning (already stopped?)", e);
            }
            return;
        }
        try {
            scheduler.unscheduleJob(new TriggerKey("SessionValidationJob", "DEFAULT"));
            if (log.isDebugEnabled())
                log.debug("Quartz session validation job stopped successfully.");
        } catch (SchedulerException e) {
            if (log.isDebugEnabled()) {
                log.debug("Could not cleanly remove SessionValidationJob from Quartz scheduler.  Ignoring and stopping.", e);
            }
 
        }
 
        this.enabled = false;
 
        if (this.schedulerImplicitlyCreated)
            try {
                scheduler.shutdown();
            } catch (SchedulerException e) {
                if (log.isWarnEnabled())
                    log.warn("Unable to cleanly shutdown implicitly created Quartz Scheduler instance.", e);
            } finally {
                setScheduler(null);
                this.schedulerImplicitlyCreated = false;
            }
    }
 
}
 
  • 修改spring配置文件
 
<bean id="sessionValidationScheduler"
      class="org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler2">
    <property name="sessionValidationInterval" value="1800000"/>
</bean>
 
  • quartz2 spring配置文件例子
 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd"
>
 
    <!-- 要调用的工作类 -->
    <bean id="quartzJob" class="com.meiya.quartz.QuartzJob"></bean>
 
    <!-- 定义调用对象和调用对象的方法 -->
    <bean id="jobtaskForToken"
          class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <!-- 调用的类 -->
        <property name="targetObject">
            <ref bean="quartzJob" />
        </property>
        <!-- 调用类中的方法 -->
        <property name="targetMethod">
            <value>workForToken</value>
        </property>
 
    </bean>
    <!-- 定义触发时间 -->
    <bean id="doTimeForToken" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean ">
        <property name="jobDetail">
            <ref bean="jobtaskForToken" />
        </property>
        <!-- cron表达式 -->
        <property name="cronExpression">
            <value>0/10 * * * * ?</value>
        </property>
    </bean>
 
    <!-- 总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序 -->
    <bean id="startQuertz" lazy-init="false" autowire="no"
          class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="doTimeForToken" />
            </list>
        </property>
    </bean>
</beans>
 
  • job类
 
package com.meiya.quartz;
 
import java.util.Date;
 
/**
* Created by 肖建锋 on 2017/1/13.
*/
public class QuartzJob {
    public void workForToken() {
        System.out.println(new Date());
    }
}
  • 修改build.gradle
 
compile ("org.quartz-scheduler:quartz:2.2.3")
compile ("org.apache.shiro:shiro-quartz:${shiro}") {
    exclude group: "org.opensymphony.quartz"
}
  • 编写java类
 
package org.apache.shiro.session.mgt.quartz;
 
/**
* Created by koko on 2016/7/20.
*/
import org.apache.shiro.session.mgt.ValidatingSessionManager;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
/**
* 基于Quartz 2.* 版本的实现
*
*/
public class QuartzSessionValidationJob2 implements Job {
 
    /**
    * Key used to store the session manager in the job data map for this job.
    */
    public static final String SESSION_MANAGER_KEY = "sessionManager";
 
    /*--------------------------------------------
    |    I N S T A N C E  V A R I A B L E S    |
    ============================================*/
    private static final Logger log = LoggerFactory.getLogger(QuartzSessionValidationJob2.class);
 
    /*--------------------------------------------
    |        C O N S T R U C T O R S          |
    ============================================*/
 
    /*--------------------------------------------
    |  A C C E S S O R S / M O D I F I E R S    |
    ============================================*/
 
    /*--------------------------------------------
    |              M E T H O D S              |
    ============================================*/
 
    /**
    * Called when the job is executed by quartz. This method delegates to the <tt>validateSessions()</tt> method on the
    * associated session manager.
    *
    * @param context
    *            the Quartz job execution context for this execution.
    */
    public void execute(JobExecutionContext context) throws JobExecutionException {
 
        JobDataMap jobDataMap = context.getMergedJobDataMap();
        ValidatingSessionManager sessionManager = (ValidatingSessionManager) jobDataMap.get(SESSION_MANAGER_KEY);
 
        if (log.isDebugEnabled()) {
            log.debug("Executing session validation Quartz job...");
        }
 
        sessionManager.validateSessions();
 
        if (log.isDebugEnabled()) {
            log.debug("Session validation Quartz job complete.");
        }
    }
 
}

 
 
package org.apache.shiro.session.mgt.quartz;
 
/**
* Created by koko on 2016/7/20.
*/
import org.apache.shiro.session.mgt.DefaultSessionManager;
import org.apache.shiro.session.mgt.SessionValidationScheduler;
import org.apache.shiro.session.mgt.ValidatingSessionManager;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
/**
* 基于Quartz 2.* 版本的实现
*/
public class QuartzSessionValidationScheduler2 implements SessionValidationScheduler {
 
    public static final long DEFAULT_SESSION_VALIDATION_INTERVAL = DefaultSessionManager.DEFAULT_SESSION_VALIDATION_INTERVAL;
    private static final String JOB_NAME = "SessionValidationJob";
    private static final Logger log = LoggerFactory.getLogger(QuartzSessionValidationScheduler2.class);
    private static final String SESSION_MANAGER_KEY = QuartzSessionValidationJob2.SESSION_MANAGER_KEY;
    private Scheduler scheduler;
    private boolean schedulerImplicitlyCreated = false;
 
    private boolean enabled = false;
    private ValidatingSessionManager sessionManager;
    private long sessionValidationInterval = DEFAULT_SESSION_VALIDATION_INTERVAL;
 
    public QuartzSessionValidationScheduler2() {
    }
 
    public QuartzSessionValidationScheduler2(ValidatingSessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }
 
    protected Scheduler getScheduler() throws SchedulerException {
        if (this.scheduler == null) {
            this.scheduler = StdSchedulerFactory.getDefaultScheduler();
            this.schedulerImplicitlyCreated = true;
        }
        return this.scheduler;
    }
 
    public void setScheduler(Scheduler scheduler) {
        this.scheduler = scheduler;
    }
 
    public void setSessionManager(ValidatingSessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }
 
    public boolean isEnabled() {
        return this.enabled;
    }
 
    public void setSessionValidationInterval(long sessionValidationInterval) {
        this.sessionValidationInterval = sessionValidationInterval;
    }
 
    public void enableSessionValidation() {
        if (log.isDebugEnabled()) {
            log.debug("Scheduling session validation job using Quartz with session validation interval of ["
                    + this.sessionValidationInterval + "]ms...");
        }
 
        try {
            SimpleTrigger trigger = TriggerBuilder.newTrigger().startNow().withIdentity(JOB_NAME, Scheduler.DEFAULT_GROUP)
                    .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInMilliseconds(sessionValidationInterval))
                    .build();//<span style="color:#ff0000;">Quartz 2中的实现</span>
 
            JobDetail detail = JobBuilder.newJob(QuartzSessionValidationJob2.class)
                    .withIdentity(JOB_NAME, Scheduler.DEFAULT_GROUP).build();
            detail.getJobDataMap().put(SESSION_MANAGER_KEY, this.sessionManager);
            Scheduler scheduler = getScheduler();
 
            scheduler.scheduleJob(detail, trigger);
            if (this.schedulerImplicitlyCreated) {
                scheduler.start();
                if (log.isDebugEnabled()) {
                    log.debug("Successfully started implicitly created Quartz Scheduler instance.");
                }
            }
            this.enabled = true;
 
            if (log.isDebugEnabled())
                log.debug("Session validation job successfully scheduled with Quartz.");
        } catch (SchedulerException e) {
            if (log.isErrorEnabled())
                log.error("Error starting the Quartz session validation job.  Session validation may not occur.", e);
        }
    }
 
    public void disableSessionValidation() {
        if (log.isDebugEnabled()) {
            log.debug("Stopping Quartz session validation job...");
        }
        Scheduler scheduler;
        try {
            scheduler = getScheduler();
            if (scheduler == null) {
                if (log.isWarnEnabled()) {
                    log.warn("getScheduler() method returned a null Quartz scheduler, which is unexpected.  Please check your configuration and/or implementation.  Returning quietly since there is no validation job to remove (scheduler does not exist).");
                }
 
                return;
            }
        } catch (SchedulerException e) {
            if (log.isWarnEnabled()) {
                log.warn("Unable to acquire Quartz Scheduler.  Ignoring and returning (already stopped?)", e);
            }
            return;
        }
        try {
            scheduler.unscheduleJob(new TriggerKey("SessionValidationJob", "DEFAULT"));
            if (log.isDebugEnabled())
                log.debug("Quartz session validation job stopped successfully.");
        } catch (SchedulerException e) {
            if (log.isDebugEnabled()) {
                log.debug("Could not cleanly remove SessionValidationJob from Quartz scheduler.  Ignoring and stopping.", e);
            }
 
        }
 
        this.enabled = false;
 
        if (this.schedulerImplicitlyCreated)
            try {
                scheduler.shutdown();
            } catch (SchedulerException e) {
                if (log.isWarnEnabled())
                    log.warn("Unable to cleanly shutdown implicitly created Quartz Scheduler instance.", e);
            } finally {
                setScheduler(null);
                this.schedulerImplicitlyCreated = false;
            }
    }
 
}
 
  • 修改spring配置文件
 
<bean id="sessionValidationScheduler"
      class="org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler2">
    <property name="sessionValidationInterval" value="1800000"/>
</bean>
 
  • quartz2 spring配置文件例子
 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd"
>
 
    <!-- 要调用的工作类 -->
    <bean id="quartzJob" class="com.meiya.quartz.QuartzJob"></bean>
 
    <!-- 定义调用对象和调用对象的方法 -->
    <bean id="jobtaskForToken"
          class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <!-- 调用的类 -->
        <property name="targetObject">
            <ref bean="quartzJob" />
        </property>
        <!-- 调用类中的方法 -->
        <property name="targetMethod">
            <value>workForToken</value>
        </property>
 
    </bean>
    <!-- 定义触发时间 -->
    <bean id="doTimeForToken" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean ">
        <property name="jobDetail">
            <ref bean="jobtaskForToken" />
        </property>
        <!-- cron表达式 -->
        <property name="cronExpression">
            <value>0/10 * * * * ?</value>
        </property>
    </bean>
 
    <!-- 总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序 -->
    <bean id="startQuertz" lazy-init="false" autowire="no"
          class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="doTimeForToken" />
            </list>
        </property>
    </bean>
</beans>
 
  • job类
 
package com.meiya.quartz;
 
import java.util.Date;
 
/**
* Created by 肖建锋 on 2017/1/13.
*/
public class QuartzJob {
    public void workForToken() {
        System.out.println(new Date());
    }
}

解决shiro和quartz2 版本冲突问题的更多相关文章

  1. spring maven项目解决依赖jar包版本冲突方案

    引入:http://blog.csdn.net/sanzhongguren/article/details/71191290 在spring reference中提到一个解决spring jar包之间 ...

  2. 解决com.android.support版本冲突问题

    原文:https://www.jianshu.com/p/0fe985a7e17e 项目中不同Module的support包版本冲突怎么办? 只需要将以下代码复制到每个模块的build.gradle( ...

  3. 在Visual Studio 中使用 <AutoGenerateBindingRedirects> 来解决引用的程序集版本冲突问题

    问题: https://stackoverflow.com/questions/42836248/using-autogeneratebindingredirects-in-visual-studio ...

  4. 11:如何解决Maven的Jar版本冲突问题

    右键 Exclude,排除冲突包

  5. maven exclusion 解决maven传递依赖中的版本冲突

    传递依赖是maven最有特色的.最为方便的优点之一,可以省了很多配置.如a 依赖 b,b 依赖c 默认 a也会依赖 c.但是也会带来隐患,如版本冲突.当然maven也考虑到解决办法,可以使用exclu ...

  6. Maven依赖版本冲突的分析及解决小结

    1:前言 做软件开发这几年遇到了许多的问题,也总结了一些问题的解决之道,之后慢慢的再遇到的都是一些重复性的问题了,当然,还有一些自己没有完全弄明白的问题.如果做的事情是重复的,遇到重复性问题的概率也就 ...

  7. git 本地库推送远程库 版本冲突的解决方法

    参考: http://blog.csdn.net/shiren1118/article/details/7761203 github上的版本和本地版本冲突的解决方法 $ git push XXX ma ...

  8. [转]SVN版本冲突解决详解

    原文地址:http://blog.csdn.net/windone0109/article/details/4857044 版权声明:本文为博主原创文章,未经博主允许不得转载. 版本冲突原因: 假设A ...

  9. SVN常见错误和版本冲突解决

    之前在Eclipse下面误删除了svn的一些插件包,后来重装了就问题重重,在这里还是建议, Windows下SVN最好使用桌面版,在文件管理器下面更新和提交. 1.常见错误整理 #, c-format ...

随机推荐

  1. 关于IE兼容问题

    针对IE6/7/8 可以分为两种模式:怪异模式(Quirks mode)和标准模式(Standards mode),在IE6以下版本下显示怪异模式,border和padding都包含在width中使用 ...

  2. 【redis专题(8)】命令语法介绍之通用KEY

    select num 数据库选择 默认有16[0到15]个数据库,默认自动选择0号数据库 move key num 移动key到num服务器 del key [key ...] 删除给定的一个或多个 ...

  3. linux命令之crontab定时执行任务

    一.crond简介 crond 是linux下用来周期性的执行某种任务或等待处理某些事件的一个守护进程,与windows下的计划任务类似,当安装完成操作系统后,默认会安装此服务 工具,并且会自动启动c ...

  4. java多线程基本概述(二十)——中断

    线程中断我们已经直到可以使用 interrupt() 方法,但是你必须要持有 Thread 对象,但是新的并发库中似乎在避免直接对 Thread 对象的直接操作,尽量使用 Executor 来执行所有 ...

  5. 设备offline时如何自动重置

    在linux底层 Linux/include/uapi/linux/usbdevice_fs.h中,重置_IO('U', 20)可以重置usb设备. 因此,我们可以在脚本中利用这个方法去重置USB 代 ...

  6. 我们一起学Docker(一)

    一.什么是Docker? Docker是一个基于LXC(Linux Container,Linux容器),以及cgroup的上层工具,通过对LXC,cgroup及相关系统命令的封装,使得用户可以非常方 ...

  7. vue+websocket+express+mongodb实战项目(实时聊天)

    继上一个项目用vuejs仿网易云音乐(实现听歌以及搜索功能)后,发现上一个项目单纯用vue的model管理十分混乱,然后我去看了看vuex,打算做一个项目练练手,又不想做一个重复的项目,这次我就放弃颜 ...

  8. [Git]09 如何为命令起外号

    Git并不会推断你输入的几个字符将会是哪条命令,不过如果想偷懒,少敲几个命令的字符,可以用 git config 为命令设置别名.来看看下面的例子: $ git config --global ali ...

  9. mui开发app之多图压缩与上传(仿qq空间说说发表)

    欲实现效果图 提出需求点: 用户可自由添加删除替换多张图片,并且显示相应缩略图,限制为8张 用户可选择压缩图或直接上传原图功能 返回提醒用户会丢失填写的信息 下面一个个实现上述需求,从简单到复杂: 需 ...

  10. phpcms笔记

    一.建立虚拟站点 1.先更改www目录下的站点名称,再找到apache, 打开"Apache2\conf\extra"下的"httpd-vhosts.conf" ...