使用Quartz来定期发送告警任务,告警Job如:
public class AlarmJob implements Job {
@Resource
private StoreRepository storeRepository;
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
// 告警逻辑
}
}
StoreRepository是Spring Boot中的bean,该Job被触发后,始终得不到该bean的实例,参考了https://blog.csdn.net/xiaobuding007/article/details/80455187
配置一个JobFactory
@Component
public class JobFactory extends AdaptableJobFactory {
/**
* AutowireCapableBeanFactory接口是BeanFactory的子类
* 可以连接和填充那些生命周期不被Spring管理的已存在的bean实例
*/
private AutowireCapableBeanFactory factory;
public JobFactory(AutowireCapableBeanFactory factory) {
this.factory = factory;
}
/**
* 创建Job实例
*/
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
// 实例化对象
Object job = super.createJobInstance(bundle);
// 进行注入(Spring管理该Bean)
factory.autowireBean(job);
//返回对象
return job;
}
}
并将该JobFactory配置到
@Configuration
@Slf4j
public class SchedulerConfig {
private JobFactory jobFactory;
public SchedulerConfig(JobFactory jobFactory){
this.jobFactory = jobFactory;
}
@Bean(name="SchedulerFactory")
public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setQuartzProperties(quartzProperties());
factory.setJobFactory(jobFactory);
return factory;
}
@Bean
public Properties quartzProperties() throws IOException {
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
//在quartz.properties中的属性被读取并注入后再初始化对象
propertiesFactoryBean.afterPropertiesSet();
return propertiesFactoryBean.getObject();
}
/*
* quartz初始化监听器
*/
@Bean
public QuartzInitializerListener executorListener() {
return new QuartzInitializerListener();
}
/*
* 通过SchedulerFactoryBean获取Scheduler的实例
*/
@Bean(name="Scheduler")
public Scheduler scheduler() throws IOException {
return schedulerFactoryBean().getScheduler();
}
}
配置完JobFactory之后,注入的问题得到解决。一开始我以为是Quartz没做好,看了一下官方的tutorial,原来人家本来没打算自动支持Spring Boot的DI。
官方tutorial:
http://www.quartz-scheduler.org/documentation/2.4.0-SNAPSHOT/tutorials/tutorial-lesson-12.html
- Spring Boot中使用Quartz:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-quartz.html
- Quartz的官方文档:http://www.quartz-scheduler.org/