Quartz 任务监控管理 中,我们知道实现的因难是Job持久化需要序列化,主要是以处下三个问题:
一、 org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean 报 java.io.NotSerializableException异常,需要自己实现QuartzJobBean。
二、dao必须要实现序列化接口,Hibernate dao不能直接继承自HibernateDaoSupport,因为HibernateDaoSupport没有实现序列化接口,只能通过SessionFactory构造HibernateTemplate。
三、当库里己存在Trigger,应用启动时会从库里加载己存在Trigger,会报java.io.InvalidObjectException: Could not find a SessionFactory named: null等SessionFactory等相关异常。因为应用每次启动的得到的SessionFactory实例是不一样的,当从库里取到的Job进行反 序列化时,Job里包含的SessionFactory与当前的SessionFactory不一致,所以为null。当时解决这问题采用了一个比较笨的 方法,在SchedulerServiceImpl增加一个初始化方法
- @PostConstruct
- public void init() throws SchedulerException{
- logger.info( "init start...................." );
- scheduler.addJob(jobDetail, true );
- logger.info( "init end......................." );
- }
- @PostConstruct
- public void init() throws SchedulerException{
- logger.info("init start...................." );
- scheduler.addJob(jobDetail, true );
- logger.info("init end......................." );
- }
并且增加
- <property name= "startupDelay" value= "60" />
- <property name= "startupDelay" value= "60" />
让QuartzScheduler延时启动,为了保证init()先执行,init()是更新Job,其实只是为了更新当前的 SessionFactory到Job中,保持Job里的SessionFactory与当前SessionFactory一致。我后来发现解决这个问题 还有一个更好的方法,在org.springframework.scheduling.quartz.SchedulerFactoryBean是可配 置的
- <property name= "overwriteExistingJobs" value= "true" />
- <property name= "jobDetails" >
- <list>
- <ref bean= "jobDetail" />
- </list>
- </property>
- <property name= "overwriteExistingJobs" value= "true" />
- <property name="jobDetails" >
- <list>
- <ref bean="jobDetail" />
- </list>
- </property>
这样就可以达到与init一样的效果。
这三个问题,经过研究探索,现在都己经不是问题了。下面我简单说说这个三个问题的解决办法。
第一个问题:org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean报NotSerializableException异常,这个 spring bug 己经在http://jira.springframework.org/browse/SPR-3797 找到解决方案,上面有牛人修改过的MethodInvokingJobDetailFactoryBean.java,详细源码请可以参考附件。哇塞,又可以POJO了。
- <?xml version= "1.0" encoding= "UTF-8" ?>
- <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" >
- <beans>
- <bean name= "quartzScheduler" class = "org.springframework.scheduling.quartz.SchedulerFactoryBean" >
- <property name= "dataSource" ref= "dataSource" />
- <property name= "applicationContextSchedulerContextKey" value= "applicationContextKey" />
- <property name= "configLocation" value= "classpath:quartz.properties" />
- <!--这个是必须的,QuartzScheduler 延时启动,应用启动完后 QuartzScheduler 再启动-->
- <property name= "startupDelay" value= "30" />
- <!--这个是可选,QuartzScheduler 启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了-->
- <property name= "overwriteExistingJobs" value= "true" />
- <property name= "jobDetails" >
- <list>
- <ref bean= "jobDetail" />
- </list>
- </property>
- </bean>
- <bean id= "jobDetail" class = "frameworkx.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean" >
- <!--shouldRecover属性为 true ,则当Quartz服务被中止后,再次启动任务时会尝试恢复执行之前未完成的所有任务-->
- <property name= "shouldRecover" value= "true" />
- <property name= "targetObject" ref= "customerService" />
- <property name= "targetMethod" value= "testMethod1" />
- </bean>
- </beans>
- <?xml version= "1.0" encoding= "UTF-8" ?>
- <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" >
- <beans>
- <bean name="quartzScheduler" class = "org.springframework.scheduling.quartz.SchedulerFactoryBean" >
- <property name="dataSource" ref= "dataSource" />
- <property name="applicationContextSchedulerContextKey" value= "applicationContextKey" />
- <property name="configLocation" value= "classpath:quartz.properties" />
- <!--这个是必须的,QuartzScheduler 延时启动,应用启动完后 QuartzScheduler 再启动-->
- <property name="startupDelay" value= "30" />
- <!--这个是可选,QuartzScheduler 启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了-->
- <property name="overwriteExistingJobs" value= "true" />
- <property name="jobDetails" >
- <list>
- <ref bean="jobDetail" />
- </list>
- </property>
- </bean>
- <bean id="jobDetail" class = "frameworkx.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean" >
- <!--shouldRecover属性为true ,则当Quartz服务被中止后,再次启动任务时会尝试恢复执行之前未完成的所有任务-->
- <property name="shouldRecover" value= "true" />
- <property name="targetObject" ref= "customerService" />
- <property name="targetMethod" value= "testMethod1" />
- </bean>
- </beans>
注意 <bean id="jobDetail" class="frameworkx.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"& gt;是修改过的MethodInvokingJobDetailFactoryBean。
第三个问题:从SchedulerServiceImpl 中去掉不需要的init() 方法,不用在SchedulerServiceImpl初始化后更新jobDeail。
- @PostConstruct
- public void init() throws SchedulerException{
- logger.info( "init start...................." );
- scheduler.addJob(jobDetail, true );
- logger.info( "init end......................." );
- }
- @PostConstruct
- public void init() throws SchedulerException{
- logger.info("init start...................." );
- scheduler.addJob(jobDetail, true );
- logger.info("init end......................." );
- }
第二个问题与第三个是互相关联的,我想到要解决这两个问题的一个方案是Job中不要包含SessionFactory就没一切OK了, 因为SessionFactory是hibernate dao的属性,而hibernate dao是SimpleService的属性,因此SimpleService不能有任何hibernate dao属性了。如此SimpleService业务方法里需要的hibernate dao又如何获取呢?对 spring 的了解,我们知道可以通过ApplicationContext获取到任何spring bean,但是在这里ApplicationContext又怎么获取呢? ... 查看org.springframework.web.context.ContextLoaderListener找到 org.springframework.web.context.ContextLoader.getCurrentWebApplicationContext() 可以获取到ApplicationContext,增加一个SpringBeanService类,实现序列化接口,通过 SpringBeanService可以获取到web己经加载的spring bean
- package com.sundoctor.example.service;
- import java.io.Serializable;
- import org.springframework.context.ApplicationContext;
- import org.springframework.stereotype.Service;
- import org.springframework.web.context.ContextLoader;
- @SuppressWarnings ( "unchecked" )
- @Service ( "springBeanService" )
- public class SpringBeanService implements Serializable{
- private static final long serialVersionUID = -2228376078979553838L;
- public <T> T getBean(Class<T> clazz,String beanName){
- ApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
- return (T)context.getBean(beanName);
- }
- }
- package com.sundoctor.example.service;
- import java.io.Serializable;
- import org.springframework.context.ApplicationContext;
- import org.springframework.stereotype.Service;
- import org.springframework.web.context.ContextLoader;
- @SuppressWarnings ( "unchecked" )
- @Service ( "springBeanService" )
- public class SpringBeanService implements Serializable{
- private static final long serialVersionUID = -2228376078979553838L;
- public <T> T getBean(Class<T> clazz,String beanName){
- ApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
- return (T)context.getBean(beanName);
- }
- }
因为Hibernate Dao不再持久到Job中,所在不再需要实现序列化接口,可以继承HibernateDaoSupport,当然也可以不继承,可以根据自己喜好的方式编写,不再有任何限制
- package com.sundoctor.example.dao;
- import org.hibernate.Session;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.orm.hibernate3.HibernateCallback;
- import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
- import org.springframework.stereotype.Repository;
- import com.sundoctor.example.model.Customer;
- import com.sundoctor.example.service.CustomerService;
- @Repository ( "customerDao" )
- public class CustomerHibernateDao extends HibernateDaoSupport {
- private static final Logger logger = LoggerFactory.getLogger(CustomerService. class );
- public Customer getCustomer2() {
- return (Customer) this .getHibernateTemplate().execute( new HibernateCallback() {
- public Object doInHibernate(Session session) {
- Customer customer = (Customer) session.createQuery( "from Customer where id = 1" ).uniqueResult();
- logger.info( "Customer2={}" , customer);
- return customer;
- }
- });
- }
- public Customer getCustomer1() {
- Customer customer = (Customer) this .getHibernateTemplate().get(Customer. class , 1 );
- logger.info( "Customer1={}" , customer);
- return customer;
- }
- }
- package com.sundoctor.example.dao;
- import org.hibernate.Session;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.orm.hibernate3.HibernateCallback;
- import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
- import org.springframework.stereotype.Repository;
- import com.sundoctor.example.model.Customer;
- import com.sundoctor.example.service.CustomerService;
- @Repository ( "customerDao" )
- public class CustomerHibernateDao extends HibernateDaoSupport {
- private static final Logger logger = LoggerFactory.getLogger(CustomerService. class );
- public Customer getCustomer2() {
- return (Customer) this .getHibernateTemplate().execute( new HibernateCallback() {
- public Object doInHibernate(Session session) {
- Customer customer = (Customer) session.createQuery("from Customer where id = 1" ).uniqueResult();
- logger.info("Customer2={}" , customer);
- return customer;
- }
- });
- }
- public Customer getCustomer1() {
- Customer customer = (Customer) this .getHibernateTemplate().get(Customer. class , 1 );
- logger.info("Customer1={}" , customer);
- return customer;
- }
- }
因为hibernate dao 不再实现序列化接口和继承自HibernateDaoSupport,不能再注入到业务类中了。在业务类中注入以上的 SpringBeanService,业务方法需要的hibernate dao通过以上的SpringBeanService.getBean获取
- package com.sundoctor.example.service;
- import java.io.Serializable;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Qualifier;
- import org.springframework.stereotype.Service;
- import com.sundoctor.example.dao.CustomerHibernateDao;
- import com.sundoctor.example.model.Customer;
- @Service ( "customerService" )
- public class CustomerService implements Serializable {
- private static final long serialVersionUID = -6857596724821490041L;
- private static final Logger logger = LoggerFactory.getLogger(CustomerService. class );
- private SpringBeanService springBeanService;
- @Autowired
- public void setSpringBeanService( @Qualifier ( "springBeanService" ) SpringBeanService springBeanService) {
- this .springBeanService = springBeanService;
- }
- public void testMethod1() {
- // 这里执行定时调度业务
- CustomerHibernateDao customerDao =springBeanService.getBean(CustomerHibernateDao. class , "customerDao" );
- Customer customer = customerDao.getCustomer1();
- logger.info( "AAAA:{}" , customer);
- }
- public void testMethod2() {
- // 这里执行定时调度业务
- CustomerHibernateDao customerDao =springBeanService.getBean(CustomerHibernateDao. class , "customerDao" );
- Customer customer = customerDao.getCustomer2();
- logger.info( "BBBB:{}" , customer);
- }
- package com.sundoctor.example.service;
- import java.io.Serializable;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Qualifier;
- import org.springframework.stereotype.Service;
- import com.sundoctor.example.dao.CustomerHibernateDao;
- import com.sundoctor.example.model.Customer;
- @Service ( "customerService" )
- public class CustomerService implements Serializable {
- private static final long serialVersionUID = -6857596724821490041L;
- private static final Logger logger = LoggerFactory.getLogger(CustomerService. class );
- private SpringBeanService springBeanService;
- @Autowired
- public void setSpringBeanService( @Qualifier ( "springBeanService" ) SpringBeanService springBeanService) {
- this .springBeanService = springBeanService;
- }
- public void testMethod1() {
- // 这里执行定时调度业务
- CustomerHibernateDao customerDao =springBeanService.getBean(CustomerHibernateDao.class , "customerDao" );
- Customer customer = customerDao.getCustomer1();
- logger.info("AAAA:{}" , customer);
- }
- public void testMethod2() {
- // 这里执行定时调度业务
- CustomerHibernateDao customerDao =springBeanService.getBean(CustomerHibernateDao.class , "customerDao" );
- Customer customer = customerDao.getCustomer2();
- logger.info("BBBB:{}" , customer);
- }
以上代码中hibernate dao 获取方法:
- CustomerHibernateDao customerDao =springBeanService.getBean(CustomerHibernateDao. class , "customerDao" )获取方法;
- CustomerHibernateDao customerDao =springBeanService.getBean(CustomerHibernateDao. class , "customerDao" )获取方法;
三个主要问题就这样解决了。