看两个版本
com.xuxueli:xxl-job-core:1.9.2
com.xuxueli:xxl-job-core:2.3.1
1,v1.9.2
这个版本没有对springboot做特殊处理
所以你必须的手动创建配置
而且,@Bean注解必须指定,启动跟销毁方法
@Configuration
@ConditionalOnClass({IJobHandler.class})
public class XxlAutoConfiguration {
。。。
@Bean(
initMethod = "start",
destroyMethod = "destroy"
)
@ConditionalOnMissingBean
public XxlJobExecutor xxlJobExecutor() {
this.log.info("XxlJobExecutor started");
XxlJobExecutor xxlJobExecutor = new XxlJobExecutor();
xxlJobExecutor.setAdminAddresses(this.adminAddresses);
xxlJobExecutor.setAppName(this.appName);
xxlJobExecutor.setIp(this.ip);
xxlJobExecutor.setPort(this.port);
xxlJobExecutor.setAccessToken(this.accessToken);
xxlJobExecutor.setLogPath(this.logPath);
xxlJobExecutor.setLogRetentionDays(this.logRetentionDays);
return xxlJobExecutor;
}
}
看下XxlJobExecutor
只是实现了ApplicationContextAware 接口,为了获取ApplicationContext
以便取得XxxHandler
public class XxlJobExecutor implements ApplicationContextAware {
public void start() throws Exception {
}
public void destroy(){}
}
具体job实现类,必须继承IJobHandler
@JobHandler(value = "xxxHandler")
@Component
public class XxxHandler extends IJobHandler {
@Autowired
BpeEngine bpeEngine;
@Override
public ReturnT<String> execute(String param) throws Exception {
。。。
}
这里有个问题
XxxHandler类必须由@Component注解加载
不能放在@Bean注解里加载
因为@Bean加载的类是在@Component后面,但同样由@Bean加载的不同类加载顺序就不一定了
因此就不能保证XxlJobExecutor的start方法在全部XxxHandler加载完在执行
2,v2.3.1
提供了一个XxlJobSpringExecutor
不必指定启动跟销毁方法
@Bean
public XxlJobSpringExecutor xxlJobExecutor() {
logger.info(">>>>>>>>>>> xxl-job config init.");
XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
xxlJobSpringExecutor.setAppname(appname);
xxlJobSpringExecutor.setAddress(address);
xxlJobSpringExecutor.setIp(ip);
xxlJobSpringExecutor.setPort(port);
xxlJobSpringExecutor.setAccessToken(accessToken);
xxlJobSpringExecutor.setLogPath(logPath);
xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays);
return xxlJobSpringExecutor;
}
看下XxlJobSpringExecutor
除了ApplicationContextAware,还实现了SmartInitializingSingleton,DisposableBean
两个接口
SmartInitializingSingleton.afterSingletonsInstantiated:会在所有的单例类被加载完后执行,也就是v1.9.2的start方法,但,可以保证所有的XxxHandler加载完后执行,当然你非要把XxxHandler弄成不是单例的就完蛋了。
DisposableBean.destroy:就是v1.9.2的销毁方法,由spring生命周期管理
public class XxlJobSpringExecutor extends XxlJobExecutor implements ApplicationContextAware, SmartInitializingSingleton, DisposableBean {
// start
@Override
public void afterSingletonsInstantiated() {}
// destroy
@Override
public void destroy() {
super.destroy();
}
}
XxxHandler 写法也变了
由v1.9.2的继承抽象类IJobHandler + 类注解@JobHandler(value = "xxxHandler")
变成了@Component + 方法注解@XxlJob("handler1")
这样比原来更灵活了
@Component
public class XxxHandler {
@XxlJob("handler1")
public void demoJobHandler() throws Exception {
}
@XxlJob("handler2")
public void shardingJobHandler() throws Exception {
}
}
网友评论