Elastic Job手动装配以及与spring boot兼容

package com.lawu.eshop.order.srv.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

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 com.lawu.eshop.order.srv.constants.JobConstant;

/**
 * Spring Boot 上下文创建完成后执行的事件监听器
 * 
 * @author Sunny
 * @date 2017年5月17日
 */
public class ApplicationReadyEventListener implements ApplicationListener {

    private Logger logger = LoggerFactory.getLogger(ApplicationReadyEventListener.class);
    
    private ApplicationContext applicationContext;
    
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
    	logger.info("ApplicationStartedEventListener is starting");
    	
    	// 获取ApplicationContext
    	setApplicationContext(event.getApplicationContext());
    	
    	//initJob();
    	
        logger.info("ApplicationStartedEventListener is started");
    }
    
	private void initJob(){
        // 获取Zookeeper注册中心
        ZookeeperRegistryCenter regCenter = getApplicationContext().getBean(ZookeeperRegistryCenter.class);
        JobConstant jobConstant = getApplicationContext().getBean(JobConstant.class);
        
        System.out.println(jobConstant.getAutomaticCancelOrder());
        System.out.println(jobConstant.getRefundRequestTime());
        
        JobCoreConfiguration coreConfig = JobCoreConfiguration.newBuilder("transactionScheduledJobtest", "0/5 * * * * ?", 1).description("事务补偿").build();
        
        // 根据类名获取
        ElasticJob elasticJob = null;
        try {
        	Class clazz = Class.forName("com.lawu.eshop.compensating.transaction.job.TransactionScheduledJob");
        	elasticJob = (ElasticJob)getApplicationContext().getBean(clazz);
        } catch (Exception e) {
        	e.printStackTrace();
        }
        
        SimpleJobConfiguration simpleJobConfig = new SimpleJobConfiguration(coreConfig, elasticJob.getClass().getCanonicalName());
        SpringJobScheduler springJobScheduler = new SpringJobScheduler(elasticJob, regCenter, LiteJobConfiguration.newBuilder(simpleJobConfig).overwrite(true).build());
        springJobScheduler.init();
    }

	private ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	private void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}
	
}

监听类,用于在初始化上下文之后,加载任务

package com.lawu.eshop.compensating.transaction.job;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.lawu.eshop.compensating.transaction.TransactionMainService;
import com.lawu.eshop.compensating.transaction.annotation.CompensatingTransactionMain;

/**
 * @author Leach
 * @date 2017/3/29
 */
@Component
public class TransactionScheduledJob implements SimpleJob, InitializingBean, ApplicationContextAware {

    private ApplicationContext applicationContext;

    private List transactionMainServiceList = new ArrayList<>();

    @Override
    public void execute(ShardingContext shardingContext) {
        for (int i = 0; i < transactionMainServiceList.size(); i++) {
            transactionMainServiceList.get(i).check();
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {

        /**
         * 创建所有加了@CompensatingTransactionMain注解service对应的消费者
         */
        Map mainTransactionServiceBeans = applicationContext.getBeansWithAnnotation(CompensatingTransactionMain.class);

        Iterator> mainIterator = mainTransactionServiceBeans.entrySet().iterator();
        while (mainIterator.hasNext()) {
            Map.Entry mainTransactionServiceBean = mainIterator.next();

            TransactionMainService transactionMainService = (TransactionMainService) mainTransactionServiceBean.getValue();

            transactionMainServiceList.add(transactionMainService);
        }
    }

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

任务类

package com.lawu.eshop.order.srv;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;

import com.lawu.eshop.order.srv.listener.ApplicationReadyEventListener;

/**
 * 订单服务启动类
 * @author Sunny
 * @date 2017/3/27
 */
@EnableDiscoveryClient
@SpringBootApplication
@ComponentScan({"com.lawu.eshop"})
@ImportResource(locations={"classpath:spring.xml"})
public class OrderSrvApplication {

    private static Logger logger = LoggerFactory.getLogger(OrderSrvApplication.class);

    public static void main(String[] args) {
        logger.info("order-srv is starting");
        SpringApplication app = new SpringApplication(OrderSrvApplication.class);
        // 添加监听器
        app.addListeners(new ApplicationReadyEventListener());
        // 启动
        app.run(args);
        logger.info("order-srv is started");
    }
}
启动类

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