Spring+quartz集群解決多服務器部署定時器重復執行的問題


一、問題描述

 

Spring自帶的Task雖然能很好使用定時任務,只需要做些簡單的配置就可以了。不過如果部署在多台服務器上的時候,這樣定時任務會在每台服務器都會執行,造成重復執行。

 

 

 

 

 

二、解決方案

 

 

Spring+quartz集群可以解決多服務器部署定時器重復執行的問題。

 

 

 

 

 

1、下載quartz的Jar包或者在Maven項目加入quartz的依賴包

 

 

不再細說,詳情可參考:

 

 

Spring4整合quartz2.2定時任務:http://fanshuyao.iteye.com/blog/2309223

 

 

 

 

 

2、建立quartz表

 

 

quartz是通過表來實現多服務器定時任務集群的,表的詳細信息在壓縮包:quartz-2.2.3-distribution.tar.gz,

 

 

路徑為:quartz-2.2.3-distribution\quartz-2.2.3\docs\dbTables

 

 

這里有很多表的SQL可執行語句,直接復制執行即可。

 

 

其中附件有quartz-2.2.3-distribution.tar.gz,是2016-07-07最新的。

 

 

 

 

 

本人使用的是Mysql,執行的是tables_mysql_innodb.sql,另外一個tables_mysql.sql沒執行,看都沒有看,哈哈。

 

 

注:最好先建完表,再執行后面的索引,不然會有警告。

 

 

里面的表詳細本人也不了解,就不說了,百度或Google吧。

 

 

 

 

 

3、新增一個Bean文件(spring-quartz.xml),如下:

 

 

 

 

 

Xml代碼  

 

 

<?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類 -->
	<bean id="quartzTask" class="com.lqy.spring.task.QuartzTask"></bean>
	
	<!-- 配置方法映射工廠類 -->
	<!-- MethodInvokingJobDetailFactoryBean不支持序列化 -->
	<!-- <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<property name="targetObject" ref="quartzTask"></property>
		<property name="targetMethod" value="startTask"></property>
		<property name="concurrent" value="false"></property>
		concurrent : false表示等上一個任務執行完后再開啟新的任務
	</bean> -->
	<!-- 配置方法映射工廠類 -->
	<bean id="jobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
	    <property name="jobClass" value="com.lqy.spring.task.QuartzTaskExtends"></property>
	    <property name="durability" value="true"></property>
	    <property name="requestsRecovery" value="true" /> 
	</bean>
	
	<!-- 配置任務高度的的時間/周期 -->
	<bean id="jobTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
		<property name="jobDetail" ref="jobDetail"></property>
		<property name="cronExpression" value="0 */1 * * * ?"></property>
		<!-- <property name="startDelay" value="3000"></property> -->
	</bean>
	
	<bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="dataSource" ref="dataSource"></property>  
		<!--可選,QuartzScheduler 啟動時更新己存在的Job,這樣就不用每次修改targetObject后刪除qrtz_job_details表對應記錄了 -->    
        <property name="overwriteExistingJobs" value="true" />    
         <!--必須的,QuartzScheduler 延時啟動,應用啟動完后 QuartzScheduler 再啟動 -->  
        <property name="startupDelay" value="30" />  
        <!-- 設置自動啟動 -->  
        <property name="autoStartup" value="true" />
        <property name="applicationContextSchedulerContextKey" value="applicationContextKey" />  
        <property name="configLocation" value="classpath:spring-quartz.properties" />  
		<property name="triggers">
			<list>
				<ref bean="jobTrigger"/>
			</list>
		</property>
	</bean>
	
</beans>

 

 

 

 

 

spring-quartz.xml文件里面主要配置的是定時任務

 

 

 

 

 

其中和一般Spring整合quartz定時任務不同的是:

 

 

(1)使用數據源:

 

 

在Bean id="schedulerFactoryBean"中使用了數據源:

 

 

Xml代碼  

 

 

<property name="dataSource" ref="dataSource"></property>  

 

 

 數據源dataSource是在Spring.xml文件配置的。

 

 

 

 

 

(2)jobDetail使用的是org.springframework.scheduling.quartz.JobDetailFactoryBean

 

 

由於集群需要把定時任務的信息寫入表,需要序列化吧,但MethodInvokingJobDetailFactoryBean 不能序列化,會報錯。

 

 

 

 

 

(3)增加spring-quartz.properties文件

 

 

Xml代碼  

 

 

#==============================================================  
#Configure Main Scheduler Properties  
#==============================================================   
org.quartz.scheduler.instanceName = defaultScheduler
org.quartz.scheduler.instanceId = AUTO

#==============================================================  
#Configure JobStore  
#============================================================== 
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.tablePrefix = QRTZ_
org.quartz.jobStore.isClustered = true
org.quartz.jobStore.clusterCheckinInterval = 20000  
org.quartz.jobStore.dataSource = myDS
org.quartz.jobStore.maxMisfiresToHandleAtATime = 1
org.quartz.jobStore.misfireThreshold = 120000
org.quartz.jobStore.txIsolationLevelSerializable = true
 
#==============================================================  
#Configure ThreadPool  
#============================================================== 
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 10
org.quartz.threadPool.threadPriority = 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true

#==============================================================
#Skip Check Update
#update:true
#not update:false
#==============================================================
org.quartz.scheduler.skipUpdateCheck = true 

#============================================================================   
# Configure Plugins    
#============================================================================      
org.quartz.plugin.triggHistory.class = org.quartz.plugins.history.LoggingJobHistoryPlugin   
org.quartz.plugin.shutdownhook.class = org.quartz.plugins.management.ShutdownHookPlugin
org.quartz.plugin.shutdownhook.cleanShutdown = true

 

 

 

 

 

這個配置文件也是Quartz的配置文件,本人也不了解,只是從網上搜索來的。本來是有數據庫的連接配置的,但由於spring配置文件已經有數據源,我就刪除掉了。

 

 

 

 

 

4、把上面的spring-quartz.xml 引入到spring.xml文件中:

 

 

Xml代碼  

 

 

<import resource="spring-quartz.xml"/>

 

 

 或者在web.xml文件加上,這種方法沒有嘗試,但應該是可以的:

 

 

Xml代碼

 

 

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml,classpath:spring-quartz.xml</param-value>
</context-param>

 

 

 

 

 

5、把項目部署到集群環境中

 

 

其實就是把項目部署到2個Tomcat中,這樣能看到定時任務是否重復執行。

 

 

Tomcat+Nginx集群詳情見:http://fanshuyao.iteye.com/blog/2309601

 

 

 

 

 

6、啟動所有Tomcat,看結果,如下:

 

 

 

 
 


 由圖可見:定時器是每分鍾的0秒執行一次

 

 

 

在2個Tomcat中,分別是一個tomcat執行一次,另一個tomcat執行一次,沒有重復執行,這樣就達到了定時器的集群效果,成功。

 

 

想到的其他方案

 

 

1.全局鎖機制

 

 

   對於只需要執行一次初始化的操作,在全局緩存中設置一個全局鎖,拿到這個鎖的節點執行相應的任務。

 

 

2.數據庫層面的狀態標記

 

 

  對於有些定時任務,我們只希望執行一次,也就是說多個節點,只有一個節點在執行這個定時任務

 

 

  可以在數據庫對這個任務進行狀態標記,根據狀態來調節節點間定時任務的執行

 

 

3.代碼分離

 

 

  如果有可能,將定時任務獨立出來,成為一個單獨的項目工程,部署單節點,避免集群部署

4.設置執行定時任務的機器名,在代碼中判斷

 

 

轉自https://blog.csdn.net/edward1987815/article/details/80417564


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM