Skip to content

Commit

Permalink
SpringBoot2.0 整合 QuartJob ,实现定时器实时管理
Browse files Browse the repository at this point in the history
  • Loading branch information
cicadasmile committed Jun 11, 2019
1 parent 518c105 commit 8845a6b
Show file tree
Hide file tree
Showing 26 changed files with 3,138 additions and 0 deletions.
96 changes: 96 additions & 0 deletions ware-quart-job/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>middle-ware-parent</artifactId>
<groupId>com.boot.parent</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.quart.job</groupId>
<artifactId>ware-quart-job</artifactId>
<packaging>jar</packaging>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring-boot.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>${spring-boot.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatisplus.version}</version>
<exclusions>
<exclusion>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>${mybatisplus.version}</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>${pagehelper.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>${quartz.version}</version>
<exclusions>
<exclusion>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda.time.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.quart.job;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class QuartJobApplication {
public static void main(String[] args) {
SpringApplication.run(QuartJobApplication.class, args);
}
}
133 changes: 133 additions & 0 deletions ware-quart-job/src/main/java/com/quart/job/config/DruidConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package com.quart.job.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
* Druid数据库连接池配置文件
*/
@Configuration
public class DruidConfig {
private static final Logger logger = LoggerFactory.getLogger(DruidConfig.class);

@Value("${spring.datasource.druid.url}")
private String dbUrl;

@Value("${spring.datasource.druid.username}")
private String username;

@Value("${spring.datasource.druid.password}")
private String password;

@Value("${spring.datasource.druid.driverClassName}")
private String driverClassName;

@Value("${spring.datasource.druid.initial-size}")
private int initialSize;

@Value("${spring.datasource.druid.max-active}")
private int maxActive;

@Value("${spring.datasource.druid.min-idle}")
private int minIdle;

@Value("${spring.datasource.druid.max-wait}")
private int maxWait;

@Value("${spring.datasource.druid.pool-prepared-statements}")
private boolean poolPreparedStatements;

@Value("${spring.datasource.druid.max-pool-prepared-statement-per-connection-size}")
private int maxPoolPreparedStatementPerConnectionSize;

@Value("${spring.datasource.druid.time-between-eviction-runs-millis}")
private int timeBetweenEvictionRunsMillis;

@Value("${spring.datasource.druid.min-evictable-idle-time-millis}")
private int minEvictableIdleTimeMillis;

@Value("${spring.datasource.druid.max-evictable-idle-time-millis}")
private int maxEvictableIdleTimeMillis;

@Value("${spring.datasource.druid.validation-query}")
private String validationQuery;

@Value("${spring.datasource.druid.test-while-idle}")
private boolean testWhileIdle;

@Value("${spring.datasource.druid.test-on-borrow}")
private boolean testOnBorrow;

@Value("${spring.datasource.druid.test-on-return}")
private boolean testOnReturn;

@Value("${spring.datasource.druid.filters}")
private String filters;

@Value("{spring.datasource.druid.connection-properties}")
private String connectionProperties;

@Bean //声明其为Bean实例
@Primary //在同样的DataSource中,首先使用被标注的DataSource
public DataSource dataSource() {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(dbUrl);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setMaxEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
datasource.setFilters(filters);
} catch (Exception e) {
logger.error("druid configuration initialization filter", e);
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
}
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean srb =
new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
//设置控制台管理用户
srb.addInitParameter("loginUsername","root");
srb.addInitParameter("loginPassword","root");
//是否可以重置数据
srb.addInitParameter("resetEnable","false");
return srb;
}
@Bean
public FilterRegistrationBean statFilter(){
//创建过滤器
FilterRegistrationBean frb =
new FilterRegistrationBean(new WebStatFilter());
//设置过滤器过滤路径
frb.addUrlPatterns("/*");
//忽略过滤的形式
frb.addInitParameter("exclusions",
"*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return frb;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package com.quart.job.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import javax.sql.DataSource;
import java.util.Properties;

@Configuration
public class ScheduleConfig {
@Bean
public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource) {
// Quartz参数配置
Properties prop = new Properties();
// Schedule调度器的实体名字
prop.put("org.quartz.scheduler.instanceName", "HuskyScheduler");
// 设置为AUTO时使用,默认的实现org.quartz.scheduler.SimpleInstanceGenerator是基于主机名称和时间戳生成。
prop.put("org.quartz.scheduler.instanceId", "AUTO");
// 线程池配置
prop.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
prop.put("org.quartz.threadPool.threadCount", "20");
prop.put("org.quartz.threadPool.threadPriority", "5");
// JobStore配置:Scheduler在运行时用来存储相关的信息
// JDBCJobStore和JobStoreTX都使用关系数据库来存储Schedule相关的信息。
// JobStoreTX在每次执行任务后都使用commit或者rollback来提交更改。
prop.put("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX");
// 集群配置:如果有多个调度器实体的话则必须设置为true
prop.put("org.quartz.jobStore.isClustered", "true");
// 集群配置:检查集群下的其他调度器实体的时间间隔
prop.put("org.quartz.jobStore.clusterCheckinInterval", "15000");
// 设置一个频度(毫秒),用于实例报告给集群中的其他实例
prop.put("org.quartz.jobStore.maxMisfiresToHandleAtATime", "1");
// 触发器触发失败后再次触犯的时间间隔
prop.put("org.quartz.jobStore.misfireThreshold", "12000");
// 数据库表前缀
prop.put("org.quartz.jobStore.tablePrefix", "qrtz_");
// 从 LOCKS 表查询一行并对这行记录加锁的 SQL 语句
prop.put("org.quartz.jobStore.selectWithLockSQL", "SELECT * FROM {0}LOCKS UPDLOCK WHERE LOCK_NAME = ?");

// 定时器工厂配置
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setDataSource(dataSource);
factory.setQuartzProperties(prop);
factory.setSchedulerName("HuskyScheduler");
factory.setStartupDelay(30);
factory.setApplicationContextSchedulerContextKey("applicationContextKey");
// 可选,QuartzScheduler 启动时更新己存在的Job
factory.setOverwriteExistingJobs(true);
// 设置自动启动,默认为true
factory.setAutoStartup(true);
return factory;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package com.quart.job.controller;

import com.quart.job.entity.ScheduleJobBean;
import com.quart.job.service.ScheduleJobService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.Date;

@RestController
@RequestMapping("/job")
public class ScheduleJobWeb {

@Resource
private ScheduleJobService scheduleJobService ;

/**
* 添加定时器
*/
@RequestMapping("/insertJob")
public ScheduleJobBean insertJob (){
ScheduleJobBean scheduleJobBean = new ScheduleJobBean() ;
scheduleJobBean.setJobId(1L);
scheduleJobBean.setBeanName("getTimeTask");
// 每分钟执行一次
scheduleJobBean.setCronExpression("0 0/1 * * * ?");
scheduleJobBean.setParams("Hello,Quart-Job");
scheduleJobBean.setStatus(0);
scheduleJobBean.setRemark("获取时间定时器");
scheduleJobBean.setCreateTime(new Date());
scheduleJobService.insert(scheduleJobBean) ;
return scheduleJobBean ;
}

/**
* 执行一次定时器
*/
@RequestMapping("/runJob")
public String runJob (){
Long jobId = 1L ;
scheduleJobService.run(jobId);
return "success" ;
}

/**
* 更新定时器
*/
@RequestMapping("/updateJob")
public String updateJob (){
Long jobId = 1L ;
ScheduleJobBean scheduleJobBean = scheduleJobService.selectByPrimaryKey(jobId) ;
scheduleJobBean.setParams("Hello,Job_Quart");
scheduleJobService.updateByPrimaryKeySelective(scheduleJobBean) ;
return "success" ;
}

/**
* 停止定时器
*/
@RequestMapping("/pauseJob")
public String pauseJob (){
Long jobId = 1L ;
scheduleJobService.pauseJob(jobId);
return "success" ;
}

/**
* 恢复定时器
*/
@RequestMapping("/resumeJob")
public String resumeJob (){
Long jobId = 1L ;
scheduleJobService.resumeJob(jobId);
return "success" ;
}

/**
* 删除定时器
*/
@RequestMapping("/deleteJob")
public String deleteJob (){
Long jobId = 1L ;
scheduleJobService.delete(jobId);
return "success" ;
}

}
Loading

0 comments on commit 8845a6b

Please sign in to comment.