Elastic Job入门示例

Elastic Job官网:http://elasticjob.io/index_zh.html

示例:Spring Boot + Elastic Job 实现一个simple任务类型

1.maven 导入相关的包


        
            com.dangdang
            elastic-job-lite-core
            2.1.5
            
                
                    org.apache.curator
                    curator-client
                
            
        
        
            com.dangdang
            elastic-job-lite-spring
            2.1.5
            
                
                    org.apache.curator
                    curator-client
                
            
        
        
            org.apache.curator
            curator-client
            2.11.1
        
    

2.相关的配置说明

RegistryCenterConfig:连接注册中心相关的配置
JobEventConfig: Event持久到DB的相关配置
SimpleJobConfig:实现SimpleJob接口的相关配置

如下图:

Elastic Job入门示例_第1张图片

3.配置代码

    

@Configuration
@ConditionalOnExpression("'${job.zookeeper.center.serverList}'.length() > 0")
public class RegistryCenterConfig {

    /**
     *
     * @param serverList zookeeper 服务地址列表
     * @param namespace 业务的命名空间,全局唯一
     * @return
     */
    @Bean(initMethod = "init")
    public ZookeeperRegistryCenter regCenter(@Value("${job.zookeeper.center.serverList}") final String serverList,
                                             @Value("${job.zookeeper.center.namespace}") final String namespace) {
        return new ZookeeperRegistryCenter(new ZookeeperConfiguration(serverList, namespace));
    }

}
import com.dangdang.ddframe.job.event.JobEventConfiguration;
import com.dangdang.ddframe.job.event.rdb.JobEventRdbConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
public class JobEventConfig {
    @Resource
    private DataSource dataSource;

    @Bean
    public JobEventConfiguration jobEventConfiguration()
    {
        return new JobEventRdbConfiguration(dataSource);
    }

}

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.event.JobEventConfiguration;
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 javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * Simple类型作业
 *  需实现SimpleJob接口。该接口仅提供单一方法用于覆盖,此方法将定时执行。
 *  与Quartz原生接口相似,但提供了弹性扩缩容和分片等功能
 *
 */
public abstract  class SimpleJobConfig implements SimpleJob {

    @Resource
    protected ZookeeperRegistryCenter regCenter;

    @Resource
    protected JobEventConfiguration jobEventConfiguration;

    /**
     * 作业启动时间的cron表达式
     *
     * @return
     */
    abstract protected String getCron();
    /**
     * 作业分片总数
     * 子类根据业务需要重写此方法
     *
     * @return
     */
    protected int getShardingTotalCount()
    {
        return 1;//default 1
    }

    /**
     * 设置分片序列号和个性化参数对照表.
     *  子类根据需要重写此方法
     *
     * 

* 分片序列号和参数用等号分隔, 多个键值对用逗号分隔. 类似map. 分片序列号从0开始, 不可大于或等于作业分片总数. 如: 0=a,1=b,2=c *

* * @return */ protected String getShardingItemParameters() { return ""; } /** * 获取执行任务实例的Class * @return * example:DemoTask.Class; */ abstract protected Class getJobClass(); /** * * @param jobClass * @param cron * @param shardingTotalCount * @param shardingItemParameters * @return */ protected LiteJobConfiguration getLiteJobConfiguration(final Class jobClass, final String cron, final int shardingTotalCount, final String shardingItemParameters) { return LiteJobConfiguration .newBuilder( new SimpleJobConfiguration( JobCoreConfiguration.newBuilder(jobClass.getName(), cron, shardingTotalCount) .shardingItemParameters(shardingItemParameters).build(), jobClass.getCanonicalName())) .overwrite(true).build(); } @PostConstruct public void simpleJobScheduler() { new SpringJobScheduler(this, regCenter, getLiteJobConfiguration(this.getJobClass(), getCron(), getShardingTotalCount(), getShardingItemParameters()), jobEventConfiguration) .init(); } }

4. Task样例类

import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 *  简单任务的示例
 */
@Configuration("DemoTask")
public class  DemoTask  extends SimpleJobConfig {

    @Value("${DemoTaskJob.cron}")
    private String cronValue;
    @Override
    protected String getCron() {
        return cronValue;
//        return "0 0/1 * * * ?";
    }

    @Override
    protected Class getJobClass() {
        return DemoTask.class;
    }

    @Override
    public void execute(ShardingContext shardingContext) {
        String execTime=""+System.currentTimeMillis();
        System.out.println("#####Begin DemoTask executed:"+execTime+"###########################################"+JSON.toJSONString(shardingContext));
        try {
            Thread.sleep(1000*60*3);
        }catch (Exception ex){
            ex.printStackTrace();
        }
        System.out.println("#####End DemoTask executed:"+execTime+", finished time:"+System.currentTimeMillis()+"###########################################"+JSON.toJSONString(shardingContext));
    }

}
5.配置文件说明
#zk config
job.zookeeper.center.serverList=127.0.0.1:2181
job.zookeeper.center.namespace=job-test

#Demo task schedule time
DemoTaskJob.cron=0 0/1 * * * ?

6.启动类

@EnableEurekaClient
@SpringBootApplication
@MapperScan("com.xxx.service.job.mapper")
@EnableScheduling
@PropertySource(value = {"classpath:business.properties"},encoding="utf-8")
public class Application extends SpringBootServletInitializer {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder application)
	{
		return application.sources(Application.class);
	}

}

7.总结:

    a.简单任务的实现,相关概念与参数的介绍后面在分析

    b.查看zookeeper上的相关信息,可借ZooInspector工具

    


你可能感兴趣的:(Elastic,Job)