data-pipeline集成quartz实现分布式调度采数任务

在大多数的情况下,我们都希望任务能按照我们预期的时间进行执行。我最常接触的是spring自带的@Scheduled注解或是使用XXL-JOB完成对采数逻辑的调度。@Scheduled注解无法直接完成分布式的任务调度,需要配合关系型数据库的行级别锁互斥,这无疑增大了设计的复杂度。使用XXL-JOB则无疑增大了data-pipeline对第三方应用的依赖。基于以上的考虑,我选择了直接集成quartz,quartz提供了基于数据库行级别锁互斥的分布式调度方案,下面罗列集成的步骤:

  • pom添加依赖:
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
 </dependency>
  • application-*.yml添加如下配置(可根据注释按照实际情况调整):
quartz:
  jobStore:
    # 数据保存方式为数据库持久化
    class: org.quartz.impl.jdbcjobstore.JobStoreTX
    # JobDataMaps是否都为String类型,默认false
    useProperties: false
    # 表的前缀,默认QRTZ_
    tablePrefix: QRTZ_
    # 是否加入集群
    isClustered: true
    # 调度实例失效的检查时间间隔 ms
    clusterCheckinInterval: 5000
    # 数据库代理类
    driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
    # 当设置为“true”时,此属性告诉Quartz 在非托管JDBC连接上调用setTransactionIsolation
    txIsolationLevelReadCommitted: true
  scheduler:
    # 调度标识名 集群中每一个实例都必须使用相同的名称
    instanceName: ClusterQuartz
    # ID设置为自动获取 每一个必须不同
    instanceId: AUTO
  threadPool:
    # 线程池的实现类(一般使用SimpleThreadPool即可满足几乎所有用户的需求)
    class: org.quartz.simpl.SimpleThreadPool
    # 指定线程数,一般设置为1-100直接的整数,根据系统资源配置
    threadCount: 5
    # 设置线程的优先级(可以是Thread.MIN_PRIORITY(即1)和Thread.MAX_PRIORITY(这是10)之间的任何int
    threadPriority: 5
  • 创建类SpringJobFactory.java,解决job中service注入为空的问题
package cn.juque.datapipeline.quartz;

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>SpringJobFactory</li>
 *     <li>解决job中service注入为空的问题。</li>
 * </ul>
 * @date 2023-04-08 21:58:32
 **/
@Component
public class SpringJobFactory extends AdaptableJobFactory {

    @Resource
    private AutowireCapableBeanFactory autowireCapableBeanFactory;

    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        Object jobInstance = super.createJobInstance(bundle);
        // 进行注入
        this.autowireCapableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
}

  • 创建配置类QuartzConfig.java
package cn.juque.datapipeline.config;

import cn.juque.datapipeline.quartz.SpringJobFactory;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Properties;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>QuartzConfig</li>
 * </ul>
 * @date 2023-04-07 15:05:33
 **/
@Configuration
public class QuartzConfig {

    @Value("${quartz.jobStore.useProperties}")
    private Boolean jobStoreUseProperties;

    @Value("${quartz.jobStore.tablePrefix}")
    private String jobStoreTablePrefix;

    @Value("${quartz.jobStore.isClustered}")
    private Boolean jobStoreIsClustered;

    @Value("${quartz.jobStore.clusterCheckinInterval}")
    private String jobStoreClusterCheckinInterval;

    @Value("${quartz.jobStore.txIsolationLevelReadCommitted}")
    private Boolean jobStoreTxIsolationLevelReadCommitted;

    @Value("${quartz.jobStore.class}")
    private String jobStoreClass;

    @Value("${quartz.jobStore.driverDelegateClass}")
    private String jobStoreDriverDelegateClass;

    @Value("${quartz.scheduler.instanceName}")
    private String schedulerInstanceName;

    @Value("${quartz.scheduler.instanceId}")
    private String schedulerInstanceId;

    @Value("${quartz.threadPool.class}")
    private String threadPoolClass;

    @Value("${quartz.threadPool.threadCount}")
    private String threadPoolThreadCount;

    @Value("${quartz.threadPool.threadPriority}")
    private String threadPoolThreadPriority;

    @Resource
    private SpringJobFactory springJobFactory;

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource) {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setDataSource(dataSource);
        Properties properties = new Properties();
        properties.put("org.quartz.jobStore.useProperties", jobStoreUseProperties);
        properties.put("org.quartz.jobStore.tablePrefix", jobStoreTablePrefix);
        properties.put("org.quartz.jobStore.isClustered", jobStoreIsClustered);
        properties.put("org.quartz.jobStore.clusterCheckinInterval", jobStoreClusterCheckinInterval);
        properties.put("org.quartz.jobStore.txIsolationLevelReadCommitted", jobStoreTxIsolationLevelReadCommitted);
        properties.put("org.quartz.jobStore.class", jobStoreClass);
        properties.put("org.quartz.jobStore.driverDelegateClass", jobStoreDriverDelegateClass);
        properties.put("org.quartz.scheduler.instanceName", schedulerInstanceName);
        properties.put("org.quartz.scheduler.instanceId", schedulerInstanceId);
        properties.put("org.quartz.threadPool.class", threadPoolClass);
        properties.put("org.quartz.threadPool.threadCount", threadPoolThreadCount);
        properties.put("org.quartz.threadPool.threadPriority", threadPoolThreadPriority);
        schedulerFactoryBean.setQuartzProperties(properties);
        schedulerFactoryBean.setSchedulerName("dpp-scheduler");
        schedulerFactoryBean.setStartupDelay(1);
        schedulerFactoryBean.setApplicationContextSchedulerContextKey("applicationContextKey");
        // QuartzScheduler 启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录
        schedulerFactoryBean.setOverwriteExistingJobs(true);
        schedulerFactoryBean.setAutoStartup(true);
        schedulerFactoryBean.setJobFactory(this.springJobFactory);
        return schedulerFactoryBean;
    }

    @Bean
    public Scheduler scheduler(DataSource dataSource) {
        return this.schedulerFactoryBean(dataSource).getScheduler();
    }
}
  • 至此,基础配置已完成。
  • 下面参考任务调度的实现,创建TaskGroupJobServiceImpl.java
package cn.juque.datapipeline.service.impl;

import cn.juque.datapipeline.constans.BusinessConstants;
import cn.juque.datapipeline.helper.TaskInfoHelper;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>TaskGroupJobjServiceImpl</li>
 * </ul>
 * @date 2023-04-07 15:12:39
 **/
@Service("taskGroupJobService")
public class TaskGroupJobServiceImpl implements Job {

    @Resource
    private TaskInfoHelper taskInfoHelper;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        String groupId = jobDataMap.getString(BusinessConstants.GROUP_ID_KEY);
        taskInfoHelper.startTask(groupId);
    }
}
  • 添加任务的逻辑,具体参考:QuartzHelper.java
/**
     * 添加任务调度
     *
     * @param groupInfo 任务组信息
     */
    public void addJob(TaskGroupInfo groupInfo) {
        JobDetail jobDetail = JobBuilder
                .newJob(TaskGroupJobServiceImpl.class)
                .withDescription(groupInfo.getGroupName())
                .withIdentity(QUARTZ_JOB_NAME + groupInfo.getId(), QUARTZ_JOB_GROUP_NAME)
                // 传递任务组ID
                .usingJobData(BusinessConstants.GROUP_ID_KEY, groupInfo.getId()).build();
        Trigger trigger;
        if (GroupExecuteTypeEnum.CORN.getCode().equals(groupInfo.getExecuteType())) {
            trigger = TriggerBuilder.newTrigger()
                    .withDescription(groupInfo.getGroupName())
                    .withIdentity(QUARTZ_TRIGGER_NAME + groupInfo.getId(), QUARTZ_TRIGGER_GROUP_NAME)
                    .startNow().withSchedule(CronScheduleBuilder.cronSchedule(groupInfo.getCron())).build();
        } else {
            trigger = TriggerBuilder.newTrigger()
                    .withDescription(groupInfo.getGroupName())
                    .withIdentity(QUARTZ_TRIGGER_NAME + groupInfo.getId(), QUARTZ_TRIGGER_GROUP_NAME)
                    .startAt(DateUtil.offsetSecond(new Date(), groupInfo.getDelaySeconds()))
                    .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(groupInfo.getDelaySeconds())).build();
        }
        try {
            this.scheduler.scheduleJob(jobDetail, trigger);
            log.info("完成任务组【{}】的调度初始化", groupInfo.getGroupName());
        } catch (Exception e) {
            log.error("任务组【{}】调度任务初始化失败", groupInfo.getGroupName(), e);
            throw new AppException(MessageEnum.SYSTEM_ERROR);
        }
    }
  • 至此完成对quartz的集成,并实现quartz对任务组的分布式调度。下面附加对Job的其他操作方法:
/**
     * 删除任务
     *
     * @param groupId 任务组ID
     */
    public void deleteJob(String groupId) {
        JobKey jobKey = JobKey.jobKey(QUARTZ_JOB_NAME + groupId, QUARTZ_JOB_GROUP_NAME);
        try {
            this.scheduler.deleteJob(jobKey);
        } catch (Exception e) {
            log.error("任务ID【{}】调度任务删除失败", groupId, e);
            throw new AppException(MessageEnum.SYSTEM_ERROR);
        }
    }

    /**
     * job是否存在
     *
     * @param groupId 任务组ID
     * @return boolean
     */
    public Boolean existsJob(String groupId) {
        JobKey jobKey = JobKey.jobKey(QUARTZ_JOB_NAME + groupId, QUARTZ_JOB_GROUP_NAME);
        try {
            return this.scheduler.checkExists(jobKey);
        } catch (Exception e) {
            log.error("任务ID【{}】调度任务删除失败", groupId, e);
            throw new AppException(MessageEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 调度一次
     *
     * @param groupId 任务组ID
     */
    public void runOnce(String groupId) {
        JobKey jobKey = JobKey.jobKey(QUARTZ_JOB_NAME + groupId, QUARTZ_JOB_GROUP_NAME);
        try {
            this.scheduler.triggerJob(jobKey);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new AppException(MessageEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 暂停任务
     *
     * @param groupId 任务组id
     */
    public void pauseJob(String groupId) {
        JobKey jobKey = JobKey.jobKey(QUARTZ_JOB_NAME + groupId, QUARTZ_JOB_GROUP_NAME);
        try {
            this.scheduler.pauseJob(jobKey);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new AppException(MessageEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 恢复任务
     *
     * @param groupId 任务组ID
     */
    public void resumeJob(String groupId) {
        JobKey jobKey = JobKey.jobKey(QUARTZ_JOB_NAME + groupId, QUARTZ_JOB_GROUP_NAME);
        try {
            this.scheduler.resumeJob(jobKey);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new AppException(MessageEnum.SYSTEM_ERROR);
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,451评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,172评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,782评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,709评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,733评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,578评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,320评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,241评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,686评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,878评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,992评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,715评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,336评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,912评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,040评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,173评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,947评论 2 355

推荐阅读更多精彩内容