- 修改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());
}
}