魔改xxl-job,彻底告别手动配置任务!( 三 )

,来配合原生的@XxlJob注解进行使用,填写这几个字段的信息:
@Target({ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)public @interface XxlRegister {String cron();String jobDesc() default "default jobDesc";String author() default "default Author";int triggerStatus() default 0;}最后,额外添加了一个triggerStatus属性 , 表示任务的默认调度状态,0为停止状态 , 1为运行状态 。
3、自动注册核心基本准备工作做完后,下面实现自动注册执行器和jobHandler的核心代码 。核心类实现ApplicationListener接口,在接收到ApplicationReadyEvent事件后开始执行自动注册逻辑 。
@Componentpublic class XxlJobAutoRegister implements ApplicationListener<ApplicationReadyEvent>,ApplicationContextAware {private static final Log log =LogFactory.get();private ApplicationContext applicationContext;@Autowiredprivate JobGroupService jobGroupService;@Autowiredprivate JobInfoService jobInfoService;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext=applicationContext;}@Overridepublic void onApplicationEvent(ApplicationReadyEvent event) {addJobGroup();//注册执行器addJobInfo();//注册任务}}自动注册执行器的代码非常简单,根据配置文件中的appNametitle精确匹配查看调度中心是否已有执行器被注册过了,如果存在则跳过,不存在则新注册一个:
private void addJobGroup() {if (jobGroupService.preciselyCheck())return;if(jobGroupService.autoRegisterGroup())log.info("auto register xxl-job group success!");}自动注册任务的逻辑则相对复杂一些,需要完成:

  • 通过applicationContext拿到spring容器中的所有bean,再拿到这些bean中所有添加了@XxlJob注解的方法
  • 对上面获取到的方法进行检查,是否添加了我们自定义的@XxlRegister注解,如果没有则跳过,不进行自动注册
  • 对同时添加了@XxlJob@XxlRegister的方法,通过执行器id和jobHandler的值判断是否已经在调度中心注册过了,如果已存在则跳过
  • 对于满足注解条件且没有注册过的jobHandler,调用接口注册到调度中心
具体代码如下:
private void addJobInfo() {List<XxlJobGroup> jobGroups = jobGroupService.getJobGroup();XxlJobGroup xxlJobGroup = jobGroups.get(0);String[] beanDefinitionNames = applicationContext.getBeanNamesForType(Object.class, false, true);for (String beanDefinitionName : beanDefinitionNames) {Object bean = applicationContext.getBean(beanDefinitionName);Map<Method, XxlJob> annotatedMethods= MethodIntrospector.selectMethods(bean.getClass(),new MethodIntrospector.MetadataLookup<XxlJob>() {@Overridepublic XxlJob inspect(Method method) {return AnnotatedElementUtils.findMergedAnnotation(method, XxlJob.class);}});for (Map.Entry<Method, XxlJob> methodXxlJobEntry : annotatedMethods.entrySet()) {Method executeMethod = methodXxlJobEntry.getKey();XxlJob xxlJob = methodXxlJobEntry.getValue();//自动注册if (executeMethod.isAnnotationPresent(XxlRegister.class)) {XxlRegister xxlRegister = executeMethod.getAnnotation(XxlRegister.class);List<XxlJobInfo> jobInfo = jobInfoService.getJobInfo(xxlJobGroup.getId(), xxlJob.value());if (!jobInfo.isEmpty()){//因为是模糊查询,需要再判断一次Optional<XxlJobInfo> first = jobInfo.stream().filter(xxlJobInfo -> xxlJobInfo.getExecutorHandler().equals(xxlJob.value())).findFirst();if (first.isPresent())continue;}XxlJobInfo xxlJobInfo = createXxlJobInfo(xxlJobGroup, xxlJob, xxlRegister);Integer jobInfoId = jobInfoService.addJobInfo(xxlJobInfo);}}}}4、自动装配创建一个配置类,用于扫描bean
@Configuration@ComponentScan(basePackages = "com.xxl.job.plus.executor")public class XxlJobPlusConfig {}将它添加到META-INF/spring.factories文件:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\com.xxl.job.plus.executor.config.XxlJobPlusConfig到这里starter的编写就完成了,可以通过maven发布jar包到本地或者私服:
mvn clean install/deploy测试新建一个springboot项目,引入我们在上面打好的包:
<dependency><groupId>com.cn.hydra</groupId><artifactId>xxljob-autoregister-spring-boot-starter</artifactId><version>0.0.1</version></dependency>application.properties中配置xxl-job的信息 , 首先是原生的配置内容:
xxl.job.admin.addresses=http://127.0.0.1:8080/xxl-job-adminxxl.job.accessToken=default_tokenxxl.job.executor.appname=xxl-job-executor-testxxl.job.executor.address=xxl.job.executor.ip=127.0.0.1xxl.job.executor.port=9999xxl.job.executor.logpath=/data/applogs/xxl-job/jobhandlerxxl.job.executor.logretentiondays=30

推荐阅读