中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot與Quartz集成實現分布式定時任務集群的代碼實例

發布時間:2020-09-22 14:57:47 來源:腳本之家 閱讀:660 作者:AlanGogogo 欄目:編程語言

Spring Boot與Quartz集成實現分布式定時任務集群

直接貼代碼

POM

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>test.daemon</groupId>
  <artifactId>clusterquartz</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>clusterquartz</name>
  <url>http://maven.apache.org</url>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.1.RELEASE</version>
    <relativePath />
  </parent>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-logging</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.0.13</version>
    </dependency>
    <dependency>
      <groupId>com.h3database</groupId>
      <artifactId>h3</artifactId>
    </dependency>
    <dependency>
      <groupId>org.quartz-scheduler</groupId>
      <artifactId>quartz</artifactId>
      <version>2.2.1</version>
    </dependency>
    <dependency>
      <groupId>org.quartz-scheduler</groupId>
      <artifactId>quartz-jobs</artifactId>
      <version>2.2.1</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

application.yml

server:
 port: 80
spring:
 datasource:
  url: jdbc:mysql://localhost:3306/quartz
  username: admin
  password: admin
  driver-class-name: com.mysql.jdbc.Driver

quartz.properties

#============================================================================
# Configure JobStore
# Using Spring datasource in SchedulerConfig.java
# Spring uses LocalDataSourceJobStore extension of JobStoreCMT
#============================================================================
org.quartz.jobStore.useProperties=false
org.quartz.jobStore.tablePrefix = QRTZ_
org.quartz.jobStore.isClustered = true
org.quartz.jobStore.clusterCheckinInterval = 5000
org.quartz.jobStore.misfireThreshold = 60000
org.quartz.jobStore.txIsolationLevelReadCommitted = true
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
#============================================================================
# Configure Main Scheduler Properties
# Needed to manage cluster instances
#============================================================================
org.quartz.scheduler.instanceName = ClusterQuartz
org.quartz.scheduler.instanceId= AUTO
org.quartz.scheduler.rmi.export = false
org.quartz.scheduler.rmi.proxy = false
org.quartz.scheduler.wrapJobExecutionInUserTransaction = false
#============================================================================
# Configure ThreadPool
# Can also be configured in spring configuration
#============================================================================
#org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
#org.quartz.threadPool.threadCount = 5
#org.quartz.threadPool.threadPriority = 5
#org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true

Spring配置類

package test.daemon.clusterquartz.config;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.Executor;
import javax.sql.DataSource;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import test.daemon.clusterquartz.quartz.QuartzJob;
@Configuration
public class SchedulerConfig {
  @Autowired
  private DataSource dataSource;
  @Bean
  public Scheduler scheduler() throws Exception {
    Scheduler scheduler = schedulerFactoryBean().getScheduler();
    scheduler.start();
    return scheduler;
  }
  @Bean
  public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
    SchedulerFactoryBean factory = new SchedulerFactoryBean();
    factory.setSchedulerName("Cluster_Scheduler");
    factory.setDataSource(dataSource);
    factory.setApplicationContextSchedulerContextKey("applicationContext");
    factory.setTaskExecutor(schedulerThreadPool());
    factory.setTriggers(trigger1().getObject());
    factory.setQuartzProperties(quartzProperties());
    return factory;
  }
  @Bean
  public Properties quartzProperties() throws IOException {
    PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
    propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
    // 在quartz.properties中的屬性被讀取并注入后再初始化對象
    propertiesFactoryBean.afterPropertiesSet();
    return propertiesFactoryBean.getObject();
  }
  @Bean
  public JobDetailFactoryBean job1() {
    JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean();
    jobDetailFactoryBean.setJobClass(QuartzJob.class);
    jobDetailFactoryBean.setDurability(true);
    jobDetailFactoryBean.setRequestsRecovery(true);
    return jobDetailFactoryBean;
  }
  @Bean
  public CronTriggerFactoryBean trigger1() {
    CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
    cronTriggerFactoryBean.setJobDetail(job1().getObject());
    cronTriggerFactoryBean.setCronExpression("0/3 * * * * ?");
    return cronTriggerFactoryBean;
  }
  @Bean
  public Executor schedulerThreadPool() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(15);
    executor.setMaxPoolSize(25);
    executor.setQueueCapacity(100);
    return executor;
  }
}

Quartz job類

package test.daemon.clusterquartz.quartz;
import java.util.Date;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.scheduling.quartz.QuartzJobBean;
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class QuartzJob extends QuartzJobBean {
  @Override
  protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
    // TODO Auto-generated method stub
    System.out.println("\nQuartz job " + new Date());
  }
}

Spring Boot啟動類

package test.daemon.clusterquartz;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Cluster {
  public static void main(String[] args) throws Exception {
    SpringApplication.run(Cluster.class, args);
  }
}

數據庫sql

可以在Quartz的lib中找到適當的數據庫生成文件來創建jdbc job store所需要的表。這些表用于Quartz在集群環境中的調度。

一些解釋

把項目復制一份,然后改掉spring server的啟動端口,啟動多個項目,可以觀察到只有一個項目的Quartz在運行。如果當前運行Quartz的服務器掛掉,另一臺會跟進執行相同的Quartz任務。

有待思考的部分

在Quartz集群環境中,時間的同步是一個重要問題,有時間需要去看一下怎么進行時間同步來確保集群的正確性。

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對億速云的支持。如果你想了解更多相關內容請查看下面相關鏈接

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

凤冈县| 东乌珠穆沁旗| 抚松县| 通城县| 东明县| 马关县| 习水县| 自治县| 永川市| 乌拉特中旗| 孝感市| 报价| 中山市| 三都| 赣榆县| 仲巴县| 长治县| 陆河县| 贡觉县| 栾城县| 和林格尔县| 忻城县| 临潭县| 汉阴县| 台东市| 平乡县| 壶关县| 太原市| 景宁| 双桥区| 那坡县| 东山县| 平阴县| 桐庐县| 怀柔区| 新丰县| 山阴县| 西贡区| 广昌县| 三亚市| 嘉荫县|