设为首页收藏本站
开启辅助访问
切换到宽版

创星网络[分享知识 传递快乐]

 找回密码
 立即注册

QQ登录

只需一步,快速开始

用新浪微博登录

只需一步,快速搞定

搜索
查看: 5485|回复: 0
打印 上一主题 下一主题

Quartz在Spring中集群

[复制链接]

我玩的应用:

跳转到指定楼层
楼主
发表于 2012-12-13 20:20:15 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
概述

虽然单个Quartz实例能给予你很好的Job调度能力,但它不能满足典型的企业需求,如可伸缩性、高可靠性满足。假如你需要故障转移的能力并能运行日益增多的 Job,Quartz集群势必成为你应用的一部分了。使用 Quartz 的集群能力可以更好的支持你的业务需求,并且即使是其中一台机器在最糟的时间崩溃了也能确保所有的 Job 得到执行。

Quartz 中集群如何工作

一个 Quartz 集群中的每个节点是一个独立的 Quartz 应用,它又管理着其他的节点。意思是你必须对每个节点分别启动或停止。不像许多应用服务器的集群,独立的 Quartz 节点并不与另一其的节点或是管理节点通信。Quartz 应用是通过数据库表来感知到另一应用的。

图:表示了每个节点直接与数据库通信,若离开数据库将对其他节点一无所知


创建Quartz数据库表

因为Quartz 集群依赖于数据库,所以必须首先创建Quartz数据库表。Quartz 包括了所有被支持的数据库平台的 SQL 脚本。在 <quartz_home>/docs/dbTables 目录下找到那些 SQL 脚本,这里的 <quartz_home> 是解压 Quartz 分发包后的目录。
这里采用的Quartz 1.6.5版本,总共12张表,不同版本,表个数可能不同。数据库为mysql,用tables_mysql_innodb.sql创建数据库表。

配置数据库连接池

1.配置jdbc.properties文件
  1. jdbc.driverClassName=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql://localhost:3306/quartz?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true
  3. jdbc.username=root
  4. jdbc.password=kfs
复制代码
2.配置applicationContext.xml文件
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.     xmlns:aop="http://www.springframework.org/schema/aop"
  5.     xmlns:tx="http://www.springframework.org/schema/tx"
  6.     xmlns:context="http://www.springframework.org/schema/context"
  7.      xmlns:jee="http://www.springframework.org/schema/jee"
  8.     xsi:schemaLocation="
  9.     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
  10.     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  11.     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
  12.     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
  13.      http://www.springframework.org/schema/jee
  14.        http://www.springframework.org/schema/jee/spring-jee-2.5.xsd"  >
  15.   
  16.    <context:component-scan base-package="com.sundoctor"/>

  17. <!-- 属性文件读入 -->
  18. <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  19. <property name="locations">
  20. <list>
  21. <value>classpath:jdbc.properties</value>
  22. </list>
  23. </property>
  24. </bean>

  25. <!-- 数据源定义,使用c3p0 连接池 -->
  26. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
  27. <property name="driverClass" value="${jdbc.driverClassName}" />       
  28. <property name="jdbcUrl" value="${jdbc.url}" />       
  29. <property name="user" value="${jdbc.username}" />       
  30. <property name="password" value="${jdbc.password}" />       
  31. <property name="initialPoolSize" value="5" />
  32. <property name="minPoolSize" value="5" />
  33. <property name="maxPoolSize" value="20" />
  34. <property name="acquireIncrement" value="2" />
  35. <property name="maxIdleTime" value="3600" />
  36. <property name="idleConnectionTestPeriod"  value="180"/>  
  37. <property name="automaticTestTable" value="C3P0TESTTABLE"/>
  38. </bean>       
  39. </beans>
复制代码
创建Job测试服务类
  1. package com.sundoctor.quartz.cluster.example;

  2. import java.io.Serializable;

  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.stereotype.Service;

  6. @Service("simpleService")
  7. public class SimpleService implements Serializable{
  8.        
  9.         private static final long serialVersionUID = 122323233244334343L;
  10.         private static final Logger logger = LoggerFactory.getLogger(SimpleService.class);
  11.        
  12.         public void testMethod1(){
  13.                 //这里执行定时调度业务
  14.                 logger.info("testMethod1.......1");
  15.         }
  16.        
  17.         public void testMethod2(){
  18.                 logger.info("testMethod2.......2");       
  19.         }
  20. }
复制代码
因为Job需要持久化到数据库中,SimpleService必须实现Serializable接口,在这里只是简单打印一下日志。

配置 Quartz 使用集群

1.配置节点的 quartz.properties 文件
  1. org.quartz.scheduler.instanceName = TestScheduler1   
  2. org.quartz.scheduler.instanceId = AUTO  

  3. org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
  4. org.quartz.threadPool.threadCount = 10
  5. org.quartz.threadPool.threadPriority = 5
  6. org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true

  7. org.quartz.jobStore.misfireThreshold = 60000
  8. org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
  9. org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate
  10. org.quartz.jobStore.tablePrefix = QRTZ_
  11. org.quartz.jobStore.maxMisfiresToHandleAtATime=10
  12. org.quartz.jobStore.isClustered = true  
  13. org.quartz.jobStore.clusterCheckinInterval = 20000
复制代码
org.quartz.scheduler.instanceName属性可为任何值,用在 JDBC JobStore 中来唯一标识实例,但是所有集群节点中必须相同。

org.quartz.scheduler.instanceId 属性为 AUTO即可,基于主机名和时间戳来产生实例 ID。

org.quartz.jobStore.class属性为 JobStoreTX,将任务持久化到数据中。因为集群中节点依赖于数据库来传播 Scheduler 实例的状态,你只能在使用 JDBC JobStore 时应用 Quartz 集群。这意味着你必须使用 JobStoreTX 或是 JobStoreCMT 作为 Job 存储;你不能在集群中使用 RAMJobStore。

org.quartz.jobStore.isClustered 属性为 true,你就告诉了 Scheduler 实例要它参与到一个集群当中。这一属性会贯穿于调度框架的始终,用于修改集群环境中操作的默认行为。

org.quartz.jobStore.clusterCheckinInterval 属性定义了Scheduler 实例检入到数据库中的频率(单位:毫秒)。Scheduler 检查是否其他的实例到了它们应当检入的时候未检入;这能指出一个失败的 Scheduler 实例,且当前 Scheduler 会以此来接管任何执行失败并可恢复的 Job。通过检入操作,Scheduler 也会更新自身的状态记录。clusterChedkinInterval 越小,Scheduler 节点检查失败的 Scheduler 实例就越频繁。默认值是 15000 (即15 秒)。

2.配置applicationContext-quartz.xml文件
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

  3. <beans>
  4.     <bean name="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
  5.         <property name="dataSource">
  6.             <ref bean="dataSource"/>
  7.         </property>
  8.         <property name="applicationContextSchedulerContextKey" value="applicationContextKey"/>
  9.         <property name="configLocation" value="classpath:quartz.properties"/>       
  10. <property name="triggers">
  11. <list>          
  12. <ref bean="trigger1"/>
  13. <ref bean="trigger2"/>       
  14. </list>
  15. </property>       
  16.     </bean>
  17.    
  18.     <bean id="jobDetail1" class="frameworkx.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
  19.         <property name="targetObject" ref="simpleService"/>
  20.         <property name="targetMethod" value="testMethod1"/>
  21. <property name="shouldRecover" value="true"/>
  22.     </bean>
  23.     <bean id="trigger1" class="org.springframework.scheduling.quartz.CronTriggerBean">
  24.         <property name="jobDetail" ref="jobDetail1"/>
  25.         <property name="cronExpression" value="0/5 * * ? * * *"/>
  26.     </bean>   
  27.   
  28.     <bean id="jobDetail2" class="frameworkx.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
  29.         <property name="targetObject" ref="simpleService"/>
  30.         <property name="targetMethod" value="testMethod2"/>
  31. <property name="shouldRecover" value="true"/>
  32.     </bean>
  33.     <bean id="trigger2" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
  34.         <property name="jobDetail" ref="jobDetail2"/>
  35.         <property name="startDelay" value="1"/>
  36.         <property name="repeatCount" value="100"/>
  37.         <property name="repeatInterval" value="1000"/>
  38.     </bean>   
  39. </beans>
复制代码
dataSource:项目中用到的数据源,里面包含了quartz用到的12张数据库表;

applicationContextSchedulerContextKey: 是org.springframework.scheduling.quartz.SchedulerFactoryBean这个类中把spring上下 文以key/value的方式存放在了quartz的上下文中了,可以用applicationContextSchedulerContextKey所 定义的key得到对应的spring上下文;

configLocation:用于指明quartz的配置文件的位置

关于Job配置,这里有两点需要注意
MethodInvokingJobDetailFactoryBean
在这里使用牛人修改后的frameworkx.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean,可以参考:http://jira.springframework.org/browse/SPR-3797。直接使用org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean会报java.io.NotSerializableException异常。

shouldRecover
shouldRecover属性必须设置为 true,当Quartz服务被中止后,再次启动或集群中其他机器接手任务时会尝试恢复执行之前未完成的所有任务。

运行Quartz集群

在相同或不同的机器上运行com.sundoctor.quartz.cluster.example.test.MainTest进行测试,在本例中只是简单打印一下日志。
  1. package com.sundoctor.quartz.cluster.example.test;

  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;

  4. public class MainTest {

  5.         /**
  6.          * @param args
  7.          */
  8.         public static void main(String[] args) {
  9.                 ApplicationContext springContext = new ClassPathXmlApplicationContext(new String[]{"classpath:applicationContext.xml","classpath:applicationContext-quartz.xml"});
  10.         }

  11. }
复制代码
Quartz 实际并不关心你是在相同的还是不同的机器上运行节点。当集群是放置在不同的机器上时,通常称之为水平集群。节点是跑在同一台机器是,称之为垂直集群。对于垂直集群,存在着单点故障的问题。这对高可用性的应用来说是个坏消息,因为一旦机器崩溃了,所有的节点也就被有效的终止了。

当你运行水平集群时,时钟应当要同步,以免出现离奇且不可预知的行为。假如时钟没能够同步,Scheduler 实例将对其他节点的状态产生混乱。有几种简单的方法来保证时钟何持同步,而且也没有理由不这么做。最简单的同步计算机时钟的方式是使用某一个 Internet 时间服务器(Internet Time Server ITS)。

没什么会阻止你在相同环境中使用集群的和非集群的 Quartz 应用。唯一要注意的是这两个环境不要混用在相同的数据库表。意思是非集群环境不要使用与集群应用相同的一套数据库表;否则将得到希奇古怪的结果,集群和非集群的 Job 都会遇到问题。

假如你让一个非集群的 Quartz 应用与集群节点并行着运行,设法使用 JobInitializationPlugin和 RAMJobStore。

from:http://go.cxweb.com.cn/m3g6i
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 转播转播 分享分享 分享淘帖
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|创星网络 ( 苏ICP备11027519号|网站地图  

GMT+8, 2024-5-2 12:08 , Processed in 0.083017 second(s), 28 queries .

Powered by Discuz! X3

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表