Elastic-job,xml配置转换成javaBean,并使用注解动态配置任务

一、传统xml配置:

elastic-job、elastic-job-lite-console使用案例:https://blog.csdn.net/qq_31289187/article/details/84843044

官网http://elasticjob.io/docs/elastic-job-lite/00-overview/

elastic-job配置参数含义http://elasticjob.io/docs/elastic-job-lite/02-guide/config-manual/

二、javaBean配置、并使用注解动态配置任务

1、pom.xml



	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		2.1.3.RELEASE
		 
	
	com.cn.dl
	springboot-elasticjob
	0.0.1-SNAPSHOT
	springboot-elasticjob
	Demo project for Spring Boot

	
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		
		
			com.dangdang
			elastic-job-lite-core
			2.1.5
		

		
			com.dangdang
			elastic-job-lite-spring
			2.1.5
		
        
			org.projectlombok
			lombok
			1.18.4
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	


2、application.properties

#elasticJob zookeeper 注册中心配置
server_lists=127.0.0.1:2181
namespace=springBootEjob
base_sleep_time_milliseconds=1000
max_sleep_time_milliseconds=3000
max_retries=3

每个配置的含义,参考:http://elasticjob.io/docs/elastic-job-lite/02-guide/config-manual/

3、ZookeeperConfig:配置注册中心

package com.cn.dl.config;

import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;

/**
 * Created by yanshao on 2019/3/14.
 */
@SpringBootConfiguration
public class ZookeeperConfig {

    @Value("${server_lists}")
    private String serverLists;

    @Value("${namespace}")
    private String namespace;

    @Value("${base_sleep_time_milliseconds}")
    private int baseSleepTimeMilliseconds;

    @Value("${max_sleep_time_milliseconds}")
    private int maxSleepTimeMilliseconds;

    @Value("${max_retries}")
    private int maxRetries;

    /**
     * 初始化注册中心
     * */
    @Bean(initMethod = "init")
    public ZookeeperRegistryCenter zookeeperRegistryCenter() {
        ZookeeperConfiguration zookeeperConfiguration = new ZookeeperConfiguration(serverLists, namespace);
        zookeeperConfiguration.setBaseSleepTimeMilliseconds(baseSleepTimeMilliseconds);
        zookeeperConfiguration.setMaxSleepTimeMilliseconds(maxSleepTimeMilliseconds);
        zookeeperConfiguration.setMaxRetries(maxRetries);
        return new ZookeeperRegistryCenter(zookeeperConfiguration);
    }
}

4、TaskJob

package com.cn.dl.annotation;

import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.lang.annotation.*;

/**
 * Created by yanshao on 2019/3/14.
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Component
public @interface TaskJob {

    @NotNull
    String jobName();
    @NotNull
    String cron();
    @NotNull
    String desc();

    boolean failover() default false;

    String shardingItemParameters() default "";

    String jobParameter() default "";

    boolean overwrite() default true;

    int shardingTotalCount() default 1;

}

      这里添加了org.springframework.stereotype.Component,为了可以在ApplicationContext中获取当前任务的bean和任务配置,其中jobName和core这两个属性不能为null。

5、RegisterEjob:在所有bean初始化之后注册任务

package com.cn.dl.config;

import com.cn.dl.annotation.TaskJob;
import com.dangdang.ddframe.job.api.ElasticJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.Optional;


/**
 * Created by yanshao on 2019/3/14.
 */
@Component
@Slf4j
public class RegisterEjob implements ApplicationContextAware,InitializingBean {

    @Autowired
    private ZookeeperRegistryCenter zookeeperRegistryCenter;

    private ApplicationContext applicationContext;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 等所有的bean初始化之后,注册任务
     * */
    @Override
    public void afterPropertiesSet() throws Exception {
        Map registerJobs = applicationContext.getBeansWithAnnotation(TaskJob.class);
        for(Map.Entry entry : registerJobs.entrySet()){
            try {
                Object object = entry.getValue();
                if(! (object instanceof ElasticJob)){
                    throw new ClassCastException("["+object.getClass().getName() + "] The class type is not com.dangdang.ddframe.job.api.ElasticJob");
                }
                TaskJob taskJob = AnnotationUtils.findAnnotation(object.getClass(),TaskJob.class);
                SpringJobScheduler springJobScheduler = new SpringJobScheduler(
                        (ElasticJob) object,
                        zookeeperRegistryCenter,
                        getJobConfiguration(taskJob,object)
                );
                springJobScheduler.init();
            }catch (Exception e){
                log.error("注册任务异常 ",e);
            }
        }
    }
    /**
     * 配置job任务
     * @param taskJob
     * @param object
     * @return
     */
    private LiteJobConfiguration getJobConfiguration(TaskJob taskJob, Object object) {

        Optional.ofNullable(taskJob.jobName()).orElseThrow(() -> new IllegalArgumentException("The jobName cannot be null !"));
        Optional.ofNullable(taskJob.cron()).orElseThrow(() -> new IllegalArgumentException("The cron cannot be null !"));
        Optional.ofNullable(taskJob.desc()).orElseThrow(() -> new IllegalArgumentException("The desc cannot be null !"));

        SimpleJobConfiguration simpleJobConfiguration = new SimpleJobConfiguration(
                JobCoreConfiguration
                        .newBuilder(taskJob.jobName(), taskJob.cron(),taskJob.shardingTotalCount())
                        .shardingItemParameters(StringUtils.isEmpty(taskJob.shardingItemParameters()) ? null : taskJob.shardingItemParameters())
                        .description(taskJob.desc())
                        .failover(taskJob.failover())
                        .jobParameter(StringUtils.isEmpty(taskJob.jobParameter()) ? null : taskJob.jobParameter())
                        .build(),
                object.getClass().getName());

        LiteJobConfiguration liteJobConfiguration = LiteJobConfiguration
                .newBuilder(simpleJobConfiguration).overwrite(taskJob.overwrite())
                .monitorExecution(true)
                .build();
        return liteJobConfiguration;
    }

}

ApplicationContextAware,InitializingBean这两个扩展接口的用法,参考:Spring中几个重要的接口应用

6、JobA:任务A

package com.cn.dl.controller;

import com.cn.dl.annotation.TaskJob;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;

import java.util.Date;

/**
 * Created by yanshao on 2019/4/19.
 */
@TaskJob(jobName = "EjobA",cron = "0/8 * * * * ? ",desc = "EjobA任务")
public class EjobA implements SimpleJob {

    @Override
    public void execute(ShardingContext shardingContext) {
        System.out.println("EjobA >>>> " + new Date());
    }

}

7、JobB:任务B

package com.cn.dl.controller;

import com.cn.dl.annotation.TaskJob;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;

import java.util.Date;

/**
 * Created by yanshao on 2019/4/19.
 */
@TaskJob(jobName = "EjobB",cron = "0/5 * * * * ? ",desc = "EjobB任务")
public class EjobB implements SimpleJob {

    @Override
    public void execute(ShardingContext shardingContext) {
        System.out.println("EjobB >>>>> " + new Date());
    }

}

注意:如果需要注册其它任务,copy JobA或者JobB就OK了!

三、测试

Elastic-job,xml配置转换成javaBean,并使用注解动态配置任务_第1张图片

 

EjobB >>>>> Fri Apr 19 13:13:20 CST 2019
2019-04-19 13:13:20.343  INFO 18408 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-04-19 13:13:20.347  INFO 18408 --- [           main] com.cn.dl.SpringbootJobApplication       : Started SpringbootJobApplication in 5.836 seconds (JVM running for 6.509)
EjobA >>>> Fri Apr 19 13:13:24 CST 2019
EjobB >>>>> Fri Apr 19 13:13:25 CST 2019
EjobB >>>>> Fri Apr 19 13:13:30 CST 2019
EjobA >>>> Fri Apr 19 13:13:32 CST 2019
EjobB >>>>> Fri Apr 19 13:13:35 CST 2019
EjobB >>>>> Fri Apr 19 13:13:40 CST 2019
EjobA >>>> Fri Apr 19 13:13:40 CST 2019
EjobB >>>>> Fri Apr 19 13:13:45 CST 2019
EjobA >>>> Fri Apr 19 13:13:48 CST 2019
EjobB >>>>> Fri Apr 19 13:13:50 CST 2019
EjobB >>>>> Fri Apr 19 13:13:55 CST 2019
EjobA >>>> Fri Apr 19 13:13:56 CST 2019
EjobB >>>>> Fri Apr 19 13:14:00 CST 2019
EjobA >>>> Fri Apr 19 13:14:00 CST 2019

       如果job触发时间是固定几小时或者更长时间,elastic-console没有触发按钮,参考:解决elastic-console在项目部署启动之后没有触发按钮

将传统的xml改成javaBean,xml配置任务改成注解动态配置,这样更加灵活!

 

你可能感兴趣的:(中间件)