Springboot 根据数据库动态生成quartz
时间: 2023-09-12 22:03:08 浏览: 277
可以利用 Spring Boot 中的 Quartz 集成来实现根据数据库动态生成 Quartz。具体实现步骤如下:
1. 在 pom.xml 文件中添加 Spring Boot Quartz 依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
```
2. 在 application.properties 文件中配置数据源连接信息:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=username
spring.datasource.password=password
```
3. 创建一个类来配置 Quartz 数据源,实现 JobStoreTX 类型:
```java
@Configuration
public class QuartzDataSourceConfig {
@Autowired
private DataSource dataSource;
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean.setDataSource(dataSource);
schedulerFactoryBean.setQuartzProperties(quartzProperties());
schedulerFactoryBean.setJobFactory(jobFactory());
return schedulerFactoryBean;
}
@Bean
public JobFactory jobFactory() {
return new AutowiringSpringBeanJobFactory();
}
@Bean
public Properties quartzProperties() {
Properties properties = new Properties();
properties.setProperty("org.quartz.scheduler.instanceName", "quartzScheduler");
properties.setProperty("org.quartz.scheduler.instanceId", "AUTO");
properties.setProperty("org.quartz.scheduler.skipUpdateCheck", "true");
properties.setProperty("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX");
properties.setProperty("org.quartz.jobStore.driverDelegateClass", "org.quartz.impl.jdbcjobstore.StdJDBCDelegate");
properties.setProperty("org.quartz.jobStore.useProperties", "false");
properties.setProperty("org.quartz.jobStore.dataSource", "myDS");
properties.setProperty("org.quartz.jobStore.tablePrefix", "QRTZ_");
properties.setProperty("org.quartz.jobStore.isClustered", "true");
properties.setProperty("org.quartz.dataSource.myDS.driver", "com.mysql.jdbc.Driver");
properties.setProperty("org.quartz.dataSource.myDS.URL", "jdbc:mysql://localhost:3306/mydb");
properties.setProperty("org.quartz.dataSource.myDS.user", "username");
properties.setProperty("org.quartz.dataSource.myDS.password", "password");
properties.setProperty("org.quartz.dataSource.myDS.maxConnections", "10");
return properties;
}
}
```
4. 定义一个实体类来表示任务信息:
```java
@Entity
@Table(name = "quartz_job")
public class QuartzJob {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String group;
@Column(nullable = false)
private String cronExpression;
@Column(nullable = false)
private String jobClass;
@Column(nullable = false)
private String description;
// 省略 getter 和 setter 方法
}
```
5. 创建一个 JobDetailFactory 类来实例化 JobDetail 对象:
```java
@Component
public class JobDetailFactory {
private static final Logger logger = LoggerFactory.getLogger(JobDetailFactory.class);
@Autowired
private Scheduler scheduler;
public JobDetail createJobDetail(QuartzJob quartzJob) {
logger.info("Create JobDetail: {}", quartzJob);
JobKey jobKey = new JobKey(quartzJob.getName(), quartzJob.getGroup());
JobDetail jobDetail = JobBuilder.newJob()
.ofType(getClass(quartzJob.getJobClass()))
.withIdentity(jobKey)
.withDescription(quartzJob.getDescription())
.storeDurably()
.build();
return jobDetail;
}
private Class<? extends Job> getClass(String jobClass) {
try {
return (Class<? extends Job>) Class.forName(jobClass);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
```
6. 创建一个 TriggerFactory 类来实例化 Trigger 对象:
```java
@Component
public class TriggerFactory {
private static final Logger logger = LoggerFactory.getLogger(TriggerFactory.class);
@Autowired
private Scheduler scheduler;
public Trigger createTrigger(QuartzJob quartzJob) {
logger.info("Create Trigger: {}", quartzJob);
JobKey jobKey = new JobKey(quartzJob.getName(), quartzJob.getGroup());
Trigger trigger = TriggerBuilder.newTrigger()
.forJob(jobKey)
.withIdentity(jobKey.getName(), "trigger_" + jobKey.getGroup())
.withDescription(quartzJob.getDescription())
.withSchedule(CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression()))
.build();
return trigger;
}
}
```
7. 创建一个 JobService 类来管理任务:
```java
@Service
public class JobService {
@Autowired
private JobDetailFactory jobDetailFactory;
@Autowired
private TriggerFactory triggerFactory;
@Autowired
private Scheduler scheduler;
@Autowired
private QuartzJobRepository quartzJobRepository;
public List<QuartzJob> getAllQuartzJobs() {
return quartzJobRepository.findAll();
}
public void addQuartzJob(QuartzJob quartzJob) {
JobDetail jobDetail = jobDetailFactory.createJobDetail(quartzJob);
Trigger trigger = triggerFactory.createTrigger(quartzJob);
try {
scheduler.scheduleJob(jobDetail, trigger);
quartzJobRepository.save(quartzJob);
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
}
public void updateQuartzJob(QuartzJob quartzJob) {
JobKey jobKey = new JobKey(quartzJob.getName(), quartzJob.getGroup());
try {
JobDetail jobDetail = scheduler.getJobDetail(jobKey);
jobDetail.getJobBuilder().ofType(getClass(quartzJob.getJobClass()));
jobDetail.getJob().withDescription(quartzJob.getDescription());
jobDetail.getJobBuilder().storeDurably();
scheduler.addJob(jobDetail, true);
Trigger oldTrigger = scheduler.getTrigger(TriggerKey.triggerKey(jobKey.getName(), "trigger_" + jobKey.getGroup()));
Trigger newTrigger = triggerFactory.createTrigger(quartzJob);
scheduler.rescheduleJob(oldTrigger.getKey(), newTrigger);
quartzJobRepository.save(quartzJob);
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
}
public void deleteQuartzJob(QuartzJob quartzJob) {
JobKey jobKey = new JobKeyartzJob.getName(), quartzJob.getGroup());
try {
scheduler.deleteJob(jobKey);
quartzJobRepository.delete(quartzJob);
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
}
private Class<? extends Job> getClass(String jobClass) {
try {
return (Class<? extends Job>) Class.forName(jobClass);
catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
```
8. 创建一个 Controller 类来处理任务的增删改查:
```java
@RestController
@RequestMapping("/jobs")
public class QuartzJobController {
@Autowired
private JobService jobService;
@GetMapping
public ResponseEntity<List<QuartzJob>> getAllQuartzJobs() {
List<QuartzJob> quartzJobs = jobService.getAllQuartzJobs();
return new ResponseEntity<>(quartzJobs, HttpStatus.OK);
}
@PostMapping
public ResponseEntity<Void> addQuartzJob(@RequestBody QuartzJob quartzJob) {
jobService.addQuartzJob(quartzJob);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@PutMapping
public ResponseEntity<Void> updateQuartzJob(@RequestBody QuartzJob quartzJob) {
jobService.updateQuartzJob(quartzJob);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@DeleteMapping
public ResponseEntity<Void> deleteQuartzJob(@RequestBody QuartzJob quartzJob) {
jobService.deleteQuartzJob(quartzJob);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
```
这样,就可以根据数据库动态生成 Quartz 任务了。
阅读全文