Elasticjob自动创建SpringJobScheduler

SpringJobScheduler是elasticjob 为调用spring bean的job类设计的scheduler,在example,需要使用代码生成bean,如下为example的代码

@Bean
    public SimpleJob simpleJob() {
    
    
        return new SpringSimpleJob(); 
    }
    
    @Bean(initMethod = "init")
    public JobScheduler simpleJobScheduler(final SimpleJob simpleJob, @Value("${simpleJob.cron}") final String cron, @Value("${simpleJob.shardingTotalCount}") final int shardingTotalCount,
                                           @Value("${simpleJob.shardingItemParameters}") final String shardingItemParameters) {
    
    
        return new SpringJobScheduler(simpleJob, regCenter, getLiteJobConfiguration(simpleJob.getClass(), cron, shardingTotalCount, shardingItemParameters), jobEventConfiguration);
    }
    
    private LiteJobConfiguration getLiteJobConfiguration(final Class<? extends SimpleJob> 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();
    }

如果对每个类都需要使用@bean来创建,还是比较麻烦的,实际上可以使用applicationContext.getbean来自动创建,以下为实现代码。

JobScheduler scheduler = null;
		Class<?> c = null;
		try {
    
    
			c = Class.forName(jobClass);
			Object b = applicationContext.getBean(c);
			// Object b = ContextUtils.getBean(jobClass);
			if (jobEventConfig == null) {
    
    

				scheduler = new SpringJobScheduler((ElasticJob) b, regCenter, liteJobConfig,
						new EmptyElasticJobListener());
				// scheduler =new JobScheduler(regCenter, liteJobConfig);
			} else {
    
    
				scheduler = new SpringJobScheduler((ElasticJob) b, regCenter, liteJobConfig, jobEventConfig);

				// scheduler = new JobScheduler(regCenter, liteJobConfig, jobEventConfig);
			}
			scheduler.getSchedulerFacade().updateJobConfiguration(liteJobConfig);
			logger.info("create SpringJobScheduler for class:" + jobClass);

		} catch (ClassNotFoundException | BeansException e) {
    
    
			logger.info("can't found class or create bean, use JobScheduler to replace SpringJobScheduler");
			if (jobEventConfig == null) {
    
    

				scheduler = new JobScheduler(regCenter, liteJobConfig);
			} else {
    
    
				scheduler = new JobScheduler(regCenter, liteJobConfig, jobEventConfig);
			}
			scheduler.getSchedulerFacade().updateJobConfiguration(liteJobConfig);

		}

		// scheduler.init();
		return scheduler;

job实现类和普通simplejob没有什么区别

@Component
public class SyncJobFromDatabaseJob implements SimpleJob {
    
    

	public String getName() {
    
    
		return this.getClass().getCanonicalName();
	}

无论是否有带@Component注解以上代码都能生成对应的scheduler。

猜你喜欢

转载自blog.csdn.net/weixin_40455124/article/details/113706180
今日推荐