分布式定时任务:Elastic-Job-Lite

Elastic-Job-Lite 是一款由 Apache 开源的轻量级分布式任务调度框架,属于 ShardingSphere 生态体系的一部分。它专注于分布式任务调度,支持弹性伸缩、分片处理、高可用等特性,且不依赖中心化架构。

一、基础

(一)核心特性
  1. 分布式协调

    通过 ZooKeeper 实现作业的分布式调度和协调,确保任务在集群环境中不重复、不遗漏地执行。

  2. 分片机制

    支持将任务拆分为多个分片(Sharding)并行执行,提升处理效率。例如:

    java 复制代码
    // 根据分片参数处理不同数据
    int shardIndex = context.getShardingItem();  // 分片索引(0,1,2...)
    String shardParam = context.getShardingParameter();  // 分片参数
  3. 弹性伸缩

    动态感知集群节点变化,自动重新分配分片。新增节点时,分片会被均匀分配到新节点;节点下线时,其分片会被其他节点接管。

  4. 多种作业类型

    • SimpleJob:简单任务,实现 SimpleJob 接口即可。
    • DataflowJob:数据流任务,支持数据抓取(fetch)和处理(process)。
    • ScriptJob:脚本任务,支持 Shell、Python 等脚本语言。
  5. 失效转移

    当作业节点崩溃时,正在执行的分片会被转移到其他节点继续执行。

  6. 幂等性保障

    通过 ZooKeeper 实现分布式锁,确保同一分片在同一时间只被一个节点执行。

(二)架构设计

Elastic-Job-Lite 采用去中心化架构:

  • 作业节点:直接部署在应用中,既是执行节点也是调度节点。
  • 注册中心:依赖 ZooKeeper 存储作业元数据和运行状态。
  • 无中心化调度器:每个节点通过注册中心协调,无需单独的调度中心。
(三)核心概念
  1. 作业(Job)

    任务的抽象,支持 Simple、Dataflow、Script 三种类型。

  2. 分片(Sharding)

    将任务拆分为多个独立的子任务,每个分片由不同的节点执行。例如:

    yaml 复制代码
    elasticjob:
      jobs:
        myJob:
          sharding-total-count: 3  # 总分片数
          sharding-item-parameters: "0=北京,1=上海,2=广州"  # 分片参数
  3. 注册中心(Registry Center)

    ZooKeeper 作为协调服务,存储作业配置、运行状态和分片信息。

  4. 作业实例(Job Instance)

    每个作业节点启动时会向注册中心注册自己,成为一个作业实例。

二、在springboot中使用Elastic-Job-Lite

(一)添加依赖

pom.xml 中添加 Elastic-Job-Lite 和 ZooKeeper 客户端依赖:

xml 复制代码
<!-- Elastic-Job-Lite Spring Boot Starter -->
<dependency>
    <groupId>org.apache.shardingsphere.elasticjob</groupId>
    <artifactId>elasticjob-lite-spring-boot-starter</artifactId>
    <version>3.0.3</version> <!-- 最新稳定版本 -->
</dependency>

<!-- ZooKeeper 客户端 -->
<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-recipes</artifactId>
    <version>5.3.0</version>
</dependency>
(二) 配置 ZooKeeper 注册中心

你提到的没错!Elastic-Job-Lite 配置 ZooKeeper 确实有三种主要方式,我之前的回答集中在 Java 代码配置 上。现在我补充完整另外两种方式:

1.YAML 配置(Spring Boot 自动配置)

最简洁的方式,通过 application.yml 配置:

yaml 复制代码
elasticjob:
  reg-center:
    server-lists: localhost:2181  # ZooKeeper 地址
    namespace: elastic-job        # 命名空间
    base-sleep-time-milliseconds: 1000  # 初始重试等待时间
    max-sleep-time-milliseconds: 3000  # 最大重试等待时间
    max-retries: 3                # 最大重试次数
    digest: ""                    # 认证信息(可选)
  
  jobs:
    mySimpleJob:
      type: SIMPLE
      class: com.example.job.MySimpleJob  # 作业类路径
      cron: "0/10 * * * * ?"              # Cron 表达式
      sharding-total-count: 3             # 分片总数
      sharding-item-parameters: "0=A,1=B,2=C"  # 分片参数
      overwrite: true                     # 覆盖注册中心配置

关键点

  • elasticjob.reg-center 配置 ZooKeeper 连接信息。
  • elasticjob.jobs 下定义具体作业,支持 SIMPLEDATAFLOWSCRIPT 等类型。
2.Java 代码配置(手动构建 Bean)

前面示例中使用的方式,适合需要灵活控制配置的场景:

java 复制代码
@Configuration
public class JobConfig {

    @Bean(initMethod = "init")
    public ZookeeperRegistryCenter regCenter() {
        ZookeeperConfiguration zkConfig = new ZookeeperConfiguration(
                "localhost:2181", "elastic-job");
        return new ZookeeperRegistryCenter(zkConfig);
    }

    @Bean(initMethod = "init")
    public SpringJobScheduler simpleJobScheduler(
            MySimpleJob mySimpleJob, ZookeeperRegistryCenter regCenter) {
        
        JobCoreConfiguration coreConfig = JobCoreConfiguration.newBuilder(
                "mySimpleJob", "0/10 * * * * ?", 3)
                .shardingItemParameters("0=A,1=B,2=C")
                .build();
                
        SimpleJobConfiguration jobConfig = new SimpleJobConfiguration(
                coreConfig, MySimpleJob.class.getCanonicalName());
                
        return new SpringJobScheduler(
                mySimpleJob, 
                regCenter, 
                LiteJobConfiguration.newBuilder(jobConfig).overwrite(true).build()
        );
    }
}

关键点

  • 手动创建 ZookeeperRegistryCenterSpringJobScheduler Bean。
  • 通过 JobCoreConfigurationSimpleJobConfiguration 构建作业配置。
(三)创建简单作业类

实现 SimpleJob 接口,定义作业逻辑:

java 复制代码
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import org.springframework.stereotype.Component;

@Component
public class MySimpleJob implements SimpleJob {
    
    @Override
    public void execute(ShardingContext shardingContext) {
        // 获取分片信息
        int shardIndex = shardingContext.getShardingItem();
        String shardParam = shardingContext.getShardingParameter();
        
        // 作业逻辑(根据分片参数处理不同数据)
        System.out.printf("分片项: %d, 参数: %s, 时间: %s%n", 
                shardIndex, shardParam, System.currentTimeMillis());
        
        // 示例:根据分片处理不同的数据
        // if (shardIndex == 0) { processGroupA(); }
        // else if (shardIndex == 1) { processGroupB(); }
    }
}
(四)配置作业

使用 @ElasticSimpleJob 注解配置作业:

java 复制代码
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import org.apache.shardingsphere.elasticjob.api.ElasticSimpleJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JobConfig {
    
    @Autowired
    private ZookeeperRegistryCenter regCenter;
    
    @Autowired
    private MySimpleJob mySimpleJob;
    
    @Bean(initMethod = "init")
    public SpringJobScheduler simpleJobScheduler() {
        // 定义作业核心配置
        JobCoreConfiguration coreConfig = JobCoreConfiguration.newBuilder(
                "mySimpleJob",      // 作业名称
                "0/10 * * * * ?",   // Cron 表达式
                3                   // 分片总数
        ).shardingItemParameters("0=A,1=B,2=C")  // 分片参数
         .build();
        
        // 定义 Simple 作业配置
        SimpleJobConfiguration simpleJobConfig = new SimpleJobConfiguration(
                coreConfig, 
                MySimpleJob.class.getCanonicalName()
        );
        
        // 定义 Lite 作业配置
        LiteJobConfiguration jobConfig = LiteJobConfiguration.newBuilder(simpleJobConfig)
                .overwrite(true)  // 允许覆盖注册中心配置
                .build();
        
        // 创建作业调度器
        return new SpringJobScheduler(mySimpleJob, regCenter, jobConfig);
    }
}
(五)配置说明
参数 说明
reg-center.server-lists ZooKeeper 服务器地址,多个地址用逗号分隔(如 host1:2181,host2:2181
reg-center.namespace 命名空间,用于隔离不同项目的作业配置
coreConfig.cron Cron 表达式,定义作业执行时间规则
coreConfig.shardingTotalCount 分片总数,决定作业拆分为多少个并行执行单元
coreConfig.shardingItemParameters 分片参数,格式为 0=A,1=B,2=C,为每个分片指定参数
相关推荐
危险、3 小时前
RabbitMQ 通过HTTP API删除队列命令
分布式·http·rabbitmq
周某某~3 小时前
windows安装RabbitMQ
分布式·rabbitmq
Bug退退退1233 小时前
RabbitMQ 高级特性之消息确认
java·分布式·rabbitmq
一只程序汪6 小时前
【如何实现分布式压测中间件】
分布式·中间件
William一直在路上7 小时前
主流分布式中间件及其选型
分布式·中间件
茫茫人海一粒沙7 小时前
理解 Confluent Schema Registry:Kafka 生态中的结构化数据守护者
分布式·kafka
hjs_deeplearning11 小时前
认知篇#10:何为分布式与多智能体?二者联系?
人工智能·分布式·深度学习·学习·agent·智能体
小毛驴85011 小时前
Windows 环境下设置 RabbitMQ 的 consumer_timeout 参数
windows·分布式·rabbitmq
述雾学java13 小时前
Spring Cloud 服务追踪实战:使用 Zipkin 构建分布式链路追踪
分布式·spring·spring cloud·zipkin