Springboot--整合定时任务quartz--集群篇
在Spring Boot中整合Quartz进行集群部署时,需要确保Quartz的数据存储方式能够支持集群环境。以下是一个基本的配置示例:
- 在
application.properties
或application.yml
中配置Quartz属性:
# 数据源配置
spring.quartz.job-store-type=jdbc
spring.quartz.jdbc.initialize-schema=always
# 集群配置
spring.quartz.properties.org.quartz.scheduler.instanceId=AUTO
spring.quartz.properties.org.quartz.scheduler.instanceName=MyScheduler
spring.quartz.properties.org.quartz.scheduler.rmi.export=false
spring.quartz.properties.org.quartz.scheduler.rmi.proxy=false
spring.quartz.properties.org.quartz.jobStore.isClustered=true
spring.quartz.properties.org.quartz.jobStore.clusterCheckinInterval=20000
spring.quartz.properties.org.quartz.jobStore.maxMisfiresToHandleAtStartup=2000
- 在
pom.xml
中添加Quartz集群所需依赖:
<!-- Quartz -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.3.2</version>
</dependency>
- 创建定时任务:
@Component
public class SampleJob extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
// 定时任务的逻辑
System.out.println("执行定时任务:" + new Date());
}
}
- 配置定时任务:
@Configuration
public class QuartzConfig {
@Bean
public JobDetail sampleJobDetail() {
return JobBuilder.newJob(SampleJob.class)
.withIdentity("sampleJob")
.usingJobData("name", "World")
.storeDurably()
.build();
}
@Bean
public Trigger sampleJobTrigger() {
SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(10)
.repeatForever();
return TriggerBuilder.newTrigger()
.forJob(sampleJobDetail())
.withIdentity("sampleTrigger")
.withSchedule(scheduleBuilder)
.build();
}
}
确保数据库中有Quartz所需的表,如果没有,可以通过设置spring.quartz.jdbc.initialize-schema
评论已关闭