elasticJob方法使用

一、引入elasticJob包

    <dependency>
      <groupId>com.dangdang</groupId>
      <artifactId>elastic-job-lite-core</artifactId>
      <version>2.1.3</version>
    </dependency>

    <dependency>
      <groupId>com.dangdang</groupId>
      <artifactId>elastic-job-lite-spring</artifactId>
      <version>2.1.3</version>
    </dependency>

application.properties配置文件信息 

elastic-job.server-lists=192.168.1.15:2181
elastic-job.namespace=mi-test-job
elastic-job.base-sleep-time-milliseconds=1000
elastic-job.max-sleep-time-milliseconds=3000
elastic-job.max-retries=3

 

二、创建job

 创建ElasticJob配置类 配置注册中心信息

@Configuration
public class ElasticJobConfig {

    @Value("${elastic-job.server-lists}")
    private String serverLists;
    @Value("${elastic-job.namespace}")
    private String namespace;
    @Value("${elastic-job.base-sleep-time-milliseconds}")
    private int baseSleepTimeMilliseconds;
    @Value("${elastic-job.max-sleep-time-milliseconds}")
    private int maxSleepTimeMilliseconds;
    @Value("${elastic-job.max-retries}")
    private int maxRetries;


    @Bean(initMethod = "init")
    public ZookeeperRegistryCenter zookeeperRegistryCenter() {
        ZookeeperConfiguration configuration = new ZookeeperConfiguration(serverLists, namespace);
        configuration.setBaseSleepTimeMilliseconds(baseSleepTimeMilliseconds);
        configuration.setMaxSleepTimeMilliseconds(maxSleepTimeMilliseconds);
        configuration.setMaxRetries(maxRetries);
        return new ZookeeperRegistryCenter(configuration);
    }

}

创建job方法

@Component
public class ElasticJobService {
    @Resource
    private ZookeeperRegistryCenter zookeeperRegistryCenter;
    @Resource
    private StrategyJob strategyJob;

 private void initStrategyJob() {
        this.initJobScheduler(this.strategyJob, String jobName, jobCron, StrategyJob.class);
    }

 /**
     * 创建JOB
     *
     * @param elasticJob
     * @param jobName
     * @param jobCron
     * @param clazz
     */
    public void initJobScheduler(final ElasticJob elasticJob, String jobName, String jobCron, Class clazz,boolean disable)  {
            logger.info("开始创建job{}"+jobName);
            SpringJobScheduler springJobScheduler = new SpringJobScheduler(elasticJob, zookeeperRegistryCenter, liteJobConfiguration(jobName, jobCron, clazz,disable));
            springJobScheduler.init();
            logger.info("创建job结束");
    }

    /**
     * JOP配置
     *
     * @param jobName
     * @param jobCron
     * @param clazz
     * @return
     */
    private LiteJobConfiguration liteJobConfiguration(String jobName, String jobCron, Class clazz, boolean disable) {
        return LiteJobConfiguration.newBuilder(
                new SimpleJobConfiguration(
                        JobCoreConfiguration.newBuilder(
                                jobName,
                                jobCron,
                                1)
                                .build(),
                        clazz.getCanonicalName()
                )).overwrite(true).disabled(disable).build();
    }

 创建具体job类实现simplejob

@Component
public class StrategyJob implements SimpleJob {

    @Override
    public void execute(ShardingContext shardingContext) {
		//具体业务方法
    }
}

 三、使用JobAPIFactory创建各类API接口

public interface ElasticJobSupport {

    /**
     * 作业配置的API
     * @return
     */
    public JobSettingsAPI getJobSettingsAPI();

    /**
     * 操作作业的API
     * @return
     */
    public JobOperateAPI getJobOperateAPI();

    /**
     * 操作分片的API
     * @return
     */
    public ShardingOperateAPI getShardingOperateAPI();

    /**
     *  作业状态展示的API
     * @return
     */
    public JobStatisticsAPI getJobStatisticsAPI();

    /**
     * 作业服务器状态展示的API
     * @return
     */
    public ServerStatisticsAPI getServerStatisticsAPI();

    /**
     * 作业分片状态展示的API
     * @return
     */
    public ShardingStatisticsAPI getShardingStatisticsAPI();
}

 

 通过 JobAPIFactory创建接口API

@Slf4j
@Service
public class ElasticJobSupportImpl implements ElasticJobSupport{

    @Value("${elastic-job.server-lists}")
    private String serverLists;

    @Value("${elastic-job.namespace}")
    private String nameSpace;

    /**
     * 作业配置的API
     * @return
     */
    @Override
    public JobSettingsAPI getJobSettingsAPI(){
        return JobAPIFactory.createJobSettingsAPI(serverLists,nameSpace, Optional.<String>fromNullable(null));
    }

    /**
     * 操作作业的API
     * @return
     */
    @Override
    public JobOperateAPI getJobOperateAPI(){
        return JobAPIFactory.createJobOperateAPI(serverLists,nameSpace,Optional.<String>fromNullable(null));
    }

    /**
     * 操作分片的API
     * @return
     */
    @Override
    public ShardingOperateAPI getShardingOperateAPI(){
        return JobAPIFactory.createShardingOperateAPI(serverLists,nameSpace,Optional.<String>fromNullable(null));
    }

    /**
     *  作业状态展示的API
     * @return
     */
    @Override
    public JobStatisticsAPI getJobStatisticsAPI(){
        return JobAPIFactory.createJobStatisticsAPI(serverLists,nameSpace,Optional.<String>fromNullable(null));
    }

    /**
     * 作业服务器状态展示的API
     * @return
     */
    @Override
    public ServerStatisticsAPI getServerStatisticsAPI(){
        return JobAPIFactory.createServerStatisticsAPI(serverLists,nameSpace,Optional.<String>fromNullable(null));
    }

    /**
     * 作业分片状态展示的API
     * @return
     */
    @Override
    public ShardingStatisticsAPI getShardingStatisticsAPI(){
        log.info("serverLists:{}", serverLists);
        log.info("nameSpace:{}",nameSpace);
        ShardingStatisticsAPI shardingStatisticsAPI = JobAPIFactory.createShardingStatisticsAPI(serverLists,nameSpace,Optional.<String>fromNullable(null));
        log.info("shardingStatisticsAPI:{}",shardingStatisticsAPI);
        return shardingStatisticsAPI;
    }
}

方法使用:

通过job名称获取job信息 更新cron表达式


    @Autowired
    private ElasticJobSupportImpl elasticJobSupport;


    JobSettingsAPI jobOperateAPI = elasticJobSupport.getJobSettingsAPI();
    JobSettings jobSettings = jobOperateAPI.getJobSettings(request.getName());
    jobSettings.setCron(cronByTime);
    jobOperateAPI.updateJobSettings(jobSettings);

 

具体每个操作API使用方法 参考elasticjob官方操作手册

http://elasticjob.io/docs/elastic-job-lite/02-guide/operation-manual/

 其中java可以手动触发定时任务执行:

JobOperateAPI jobAPIService= JobAPIFactory.createJobOperateAPI("zookeeper地址", "任务命名空间", Optional.fromNullable(null));
jobAPIService.trigger(Optional.of("定时任务类的全类名"), Optional.<String>absent());

引入com.google.common.base.Optional

扩展:

cron表达式生成工具类

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by admin on 2017/10/23.
 */
public class DateUtil {
    private static final String CRON_DATE_FORMAT = "ss mm HH dd MM ? yyyy";

    /***
     * @param date 时间
     * @return cron类型的日期
     */
    public static String getCron(final Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(CRON_DATE_FORMAT);
        String formatTimeStr = "";
        if (date != null) {
            formatTimeStr = sdf.format(date);
        }
        return formatTimeStr;
    }
}
 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值