项目结构: 

ZookeeperProperties :读取application.yml中的自定义配置

package com.lucifer.study.autoconfig;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * @author lucifer
 * @date 2020/5/5 16:46
 * @description 读取配置文件中自定义配置
 */
@Data
@ConfigurationProperties(prefix = "elasticjob.zookeeper")
public class ZookeeperProperties {

    //zookeeper地址列表
    private String serverList;
    //zookeeper命名空间
    private String nameSpace;

}

ZookeeperAutoConfig:zookeeper自动注册

package com.lucifer.study.autoconfig;

import com.dangdang.ddframe.job.reg.base.CoordinatorRegistryCenter;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author lucifer
 * @date 2020/5/5 16:54
 * @description TODO
 */
@Configuration
@EnableConfigurationProperties(ZookeeperProperties.class)
@ConditionalOnProperty("elasticjob.zookeeper.server-list")
public class ZookeeperAutoConfig {

    @Resource
    private ZookeeperProperties zookeeperProperties;

    /**
     * zookeeper注册中心
     *
     * @return
     */
    @Bean(initMethod = "init")
    public CoordinatorRegistryCenter zkCenter() {
        String serverList = zookeeperProperties.getServerList();
        String nameSpace = zookeeperProperties.getNameSpace();
        ZookeeperConfiguration zookeeperConfiguration =
                new ZookeeperConfiguration(serverList, nameSpace);

        CoordinatorRegistryCenter coordinatorRegistryCenter =
                new ZookeeperRegistryCenter(zookeeperConfiguration);
        //注册中心初始化
        coordinatorRegistryCenter.init();
        return coordinatorRegistryCenter;
    }

}

ps:@ConditionalOnProperty注解,当elasticjob.zookeeper.server-list有值,才会生效。

在resources文件夹下,创建META-INF,创建spring.factories文件:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.lucifer.study.autoconfig.ZookeeperAutoConfig,\
com.lucifer.study.autoconfig.SimpleJobAutoConfig

application.yml:

elasticjob:
  zookeeper:
    name-space: springboot-elasticjob
    server-list: 192.168.24.128:2181

ElasticSimpleJob:自定义注解,并在其中加上@Componet注解。

package com.lucifer.study.autoconfig;

import org.springframework.stereotype.Component;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Component
public @interface ElasticSimpleJob {
    String jobName() default "";

    String cron() default "";

    int shardingTotalCount() default 1;

    boolean overwrite() default false;
}

SimpleJobAutoConfig:job的自动配置

package com.lucifer.study.autoconfig;

import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.JobTypeConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.api.JobScheduler;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.reg.base.CoordinatorRegistryCenter;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;

/**
 * @author lucifer
 * @date 2020/5/5 17:27
 * @description TODO
 */
@Configuration
@ConditionalOnBean(CoordinatorRegistryCenter.class)
@AutoConfigureAfter(ZookeeperAutoConfig.class)
public class SimpleJobAutoConfig {

    @Resource
    private CoordinatorRegistryCenter zkCenter;

    @Resource
    private ApplicationContext applicationContext;

    @PostConstruct
    public void initSimpleJob() {
        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(ElasticSimpleJob.class);
        for (Map.Entry<String, Object> entry : beans.entrySet()) {
            Object instance = entry.getValue();
            Class<?>[] interfaces = instance.getClass().getInterfaces();
            for (Class<?> anInterface : interfaces) {
                if (anInterface == SimpleJob.class) {
                    ElasticSimpleJob annotation = instance.getClass().getAnnotation(ElasticSimpleJob.class);
                    String jobName = annotation.jobName();
                    String cron = annotation.cron();
                    boolean overwrite = annotation.overwrite();
                    int shardingTotalCount = annotation.shardingTotalCount();

                    //job核心配置
                    JobCoreConfiguration jobCoreConfiguration = JobCoreConfiguration
                            .newBuilder(jobName, cron, shardingTotalCount)
                            .build();

                    //job类型配置
                    JobTypeConfiguration jobTypeConfiguration =
                            new SimpleJobConfiguration(jobCoreConfiguration, instance.getClass().getCanonicalName());

                    //job根的配置(LiteJobConfiguration)
                    LiteJobConfiguration liteJobConfiguration = LiteJobConfiguration
                            .newBuilder(jobTypeConfiguration)
                            .overwrite(overwrite)
                            .build();

                    new JobScheduler(zkCenter, liteJobConfiguration).init();
                }
            }

        }
    }

}

ps:

     1、@ConditionalOnBean(仅仅在当前上下文中存在某个对象时,才会实例化一个Bean)。

     2、被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行。

MySimpleJob : 

package com.lucifer.study.job;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.lucifer.study.autoconfig.ElasticSimpleJob;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lucifer
 * @date 2020/5/5 17:20
 * @description TODO
 */
@ElasticSimpleJob(
        jobName = "mySimpleJob",
        cron = "0/10 * * * * ?",
        shardingTotalCount = 2,
        overwrite = true
)
@Slf4j
public class MySimpleJob implements SimpleJob {
    @Override
    public void execute(ShardingContext shardingContext) {
        log.info("分片项:{},总分片数:{}",
                shardingContext.getShardingItem(),
                shardingContext.getShardingTotalCount()
        );
    }
}

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.lucifer</groupId>
    <artifactId>elastic-job-study</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>elastic-job-study</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.dangdang</groupId>
            <artifactId>elastic-job-lite-core</artifactId>
            <version>2.1.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

控制台打印:

2020-05-05 18:12:03.052  INFO 11392 --- [           main] c.d.d.j.l.i.s.JobShutdownHookPlugin      : Registering Quartz shutdown hook.
2020-05-05 18:12:03.053  INFO 11392 --- [           main] org.quartz.simpl.RAMJobStore             : RAMJobStore initialized.
2020-05-05 18:12:03.053  INFO 11392 --- [           main] org.quartz.core.QuartzScheduler          : Scheduler meta-data: Quartz Scheduler (v2.3.2) 'mySimpleJob' with instanceId 'NON_CLUSTERED'
  Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
  NOT STARTED.
  Currently in standby mode.
  Number of jobs executed: 0
  Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 1 threads.
  Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.

2020-05-05 18:12:03.053  INFO 11392 --- [           main] org.quartz.impl.StdSchedulerFactory      : Quartz scheduler 'mySimpleJob' initialized from an externally provided properties instance.
2020-05-05 18:12:03.053  INFO 11392 --- [           main] org.quartz.impl.StdSchedulerFactory      : Quartz scheduler version: 2.3.2
2020-05-05 18:12:03.105  INFO 11392 --- [           main] org.quartz.core.QuartzScheduler          : Scheduler mySimpleJob_$_NON_CLUSTERED started.
2020-05-05 18:12:03.156  INFO 11392 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-05-05 18:12:03.158  INFO 11392 --- [           main] c.l.study.ElasticJobStudyApplication     : Started ElasticJobStudyApplication in 11.163 seconds (JVM running for 12.072)
2020-05-05 18:12:10.071  INFO 11392 --- [b-mySimpleJob-1] com.lucifer.study.job.MySimpleJob        : 分片项:0,总分片数:2
2020-05-05 18:12:10.071  INFO 11392 --- [b-mySimpleJob-2] com.lucifer.study.job.MySimpleJob        : 分片项:1,总分片数:2
2020-05-05 18:12:20.015  INFO 11392 --- [b-mySimpleJob-3] com.lucifer.study.job.MySimpleJob        : 分片项:0,总分片数:2
2020-05-05 18:12:20.015  INFO 11392 --- [b-mySimpleJob-4] com.lucifer.study.job.MySimpleJob        : 分片项:1,总分片数:2

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐