如何集合SpringBoot+Quartz+数据库存储
短信预约 -IT技能 免费直播动态提醒
这篇文章主要介绍如何集合SpringBoot+Quartz+数据库存储,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
官网:http://www.quartz-scheduler.org/
我们所需数据库
pom依赖
<artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> <version>2.2.1</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> </dependencies> <build> <resources> <resource> <directory>class="lazy" data-src/main/resources</directory> </resource> <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题--> <resource> <directory>class="lazy" data-src/main/java</directory> <includes> <include>**@Component@Slf4jpublic class MyJobFactory extends AdaptableJobFactory { //这个对象Spring会帮我们自动注入进来 @Autowired private AutowireCapableBeanFactory autowireCapableBeanFactory; //重写创建Job任务的实例方法 @Override protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { Object jobInstance = super.createJobInstance(bundle); //通过以下方式,解决Job任务无法使用Spring中的Bean问题 autowireCapableBeanFactory.autowireBean(jobInstance); return super.createJobInstance(bundle); }}
DruidConnectionProvider
package com.wsy.quartz02.utils;import com.alibaba.druid.pool.DruidDataSource;import org.quartz.SchedulerException;import org.quartz.utils.ConnectionProvider;import java.sql.Connection;import java.sql.SQLException;public class DruidConnectionProvider implements ConnectionProvider { //JDBC驱动 public String driver; //JDBC连接串 public String URL; //数据库用户名 public String user; //数据库用户密码 public String password; //数据库最大连接数 public int maxConnection; //数据库SQL查询每次连接返回执行到连接池,以确保它仍然是有效的。 public String validationQuery; private boolean validateOnCheckout; private int idleConnectionValidationSeconds; public String maxCachedStatementsPerConnection; private String discardIdleConnectionsSeconds; public static final int DEFAULT_DB_MAX_CONNECTIONS = 10; public static final int DEFAULT_DB_MAX_CACHED_STATEMENTS_PER_CONNECTION = 120; //Druid连接池 private DruidDataSource datasource; public Connection getConnection() throws SQLException { return datasource.getConnection(); } public void shutdown() throws SQLException { datasource.close(); } public void initialize() throws SQLException{ if (this.URL == null) { throw new SQLException("DBPool could not be created: DB URL cannot be null"); } if (this.driver == null) { throw new SQLException("DBPool driver could not be created: DB driver class name cannot be null!"); } if (this.maxConnection < 0) { throw new SQLException("DBPool maxConnectins could not be created: Max connections must be greater than zero!"); } datasource = new DruidDataSource(); try{ datasource.setDriverClassName(this.driver); } catch (Exception e) { try { throw new SchedulerException("Problem setting driver class name on datasource: " + e.getMessage(), e); } catch (SchedulerException e1) { } } datasource.setUrl(this.URL); datasource.setUsername(this.user); datasource.setPassword(this.password); datasource.setMaxActive(this.maxConnection); datasource.setMinIdle(1); datasource.setMaxWait(0); datasource.setMaxPoolPreparedStatementPerConnectionSize(this.DEFAULT_DB_MAX_CACHED_STATEMENTS_PER_CONNECTION); if (this.validationQuery != null) { datasource.setValidationQuery(this.validationQuery); if(!this.validateOnCheckout) datasource.setTestOnReturn(true); else datasource.setTestOnBorrow(true); datasource.setValidationQueryTimeout(this.idleConnectionValidationSeconds); } } public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public String getURL() { return URL; } public void setURL(String URL) { this.URL = URL; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getMaxConnection() { return maxConnection; } public void setMaxConnection(int maxConnection) { this.maxConnection = maxConnection; } public String getValidationQuery() { return validationQuery; } public void setValidationQuery(String validationQuery) { this.validationQuery = validationQuery; } public boolean isValidateOnCheckout() { return validateOnCheckout; } public void setValidateOnCheckout(boolean validateOnCheckout) { this.validateOnCheckout = validateOnCheckout; } public int getIdleConnectionValidationSeconds() { return idleConnectionValidationSeconds; } public void setIdleConnectionValidationSeconds(int idleConnectionValidationSeconds) { this.idleConnectionValidationSeconds = idleConnectionValidationSeconds; } public DruidDataSource getDatasource() { return datasource; } public void setDatasource(DruidDataSource datasource) { this.datasource = datasource; }}
application.yml
server: servlet: context-path: / port: 80spring: datasource: #1.JDBC type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=utf8 username: root password: 123 druid: #2.连接池配置 #初始化连接池的连接数量 大小,最小,最大 initial-size: 5 min-idle: 5 max-active: 20 #配置获取连接等待超时的时间 max-wait: 60000 #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 time-between-eviction-runs-millis: 60000 # 配置一个连接在池中最小生存的时间,单位是毫秒 min-evictable-idle-time-millis: 30000 validation-query: SELECT 1 FROM DUAL test-while-idle: true test-on-borrow: true test-on-return: false # 是否缓存preparedStatement,也就是PSCache 官方建议MySQL下建议关闭 个人建议如果想用SQL防火墙 建议打开 pool-prepared-statements: true max-pool-prepared-statement-per-connection-size: 20 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 filter: stat: merge-sql: true slow-sql-millis: 5000 #3.基础监控配置 web-stat-filter: enabled: true url-pattern: List<ScheduleTrigger> queryScheduleTriggerLst();}
ScheduleTriggerParamMapper
package com.wsy.quartz02.mapper;import com.wsy.quartz02.model.ScheduleTriggerParam;import org.springframework.stereotype.Repository;import java.util.List;@Repositorypublic interface ScheduleTriggerParamMapper { int deleteByPrimaryKey(Integer param_id); int insert(ScheduleTriggerParam record); int insertSelective(ScheduleTriggerParam record); ScheduleTriggerParam selectByPrimaryKey(Integer param_id); int updateByPrimaryKeySelective(ScheduleTriggerParam record); int updateByPrimaryKey(ScheduleTriggerParam record); List<ScheduleTriggerParam> queryScheduleParamLst(Integer triggerId);}
ScheduleTriggerParam
<select id="queryScheduleParamLst" resultType="com.wsy.quartz02.model.ScheduleTriggerParam"> select <include refid="Base_Column_List"/> from t_schedule_trigger_param where schedule_trigger_id=#{triggerId} </select>
ScheduleTrigger
<select id="queryScheduleTriggerLst" resultType="com.wsy.quartz02.model.ScheduleTrigger"> select <include refid="Base_Column_List"/> from t_schedule_trigger </select>
QuartzConfiguration
package com.wsy.config;import com.wsy.quartz02.utils.MyJobFactory;import org.quartz.Scheduler;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.config.PropertiesFactoryBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.io.ClassPathResource;import org.springframework.scheduling.quartz.SchedulerFactoryBean;import java.io.IOException;import java.util.Properties;@Configurationpublic class QuartzConfiguration { @Autowired private MyJobFactory myJobFactory; //创建调度器工厂 @Bean public SchedulerFactoryBean schedulerFactoryBean(){ //1.创建SchedulerFactoryBean //2.加载自定义的quartz.properties配置文件 //3.设置MyJobFactory SchedulerFactoryBean factoryBean=new SchedulerFactoryBean(); try { factoryBean.setQuartzProperties(quartzProperties()); factoryBean.setJobFactory(myJobFactory); return factoryBean; } catch (IOException e) { throw new RuntimeException(e); } } public Properties quartzProperties() throws IOException { PropertiesFactoryBean propertiesFactoryBean=new PropertiesFactoryBean(); propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties")); propertiesFactoryBean.afterPropertiesSet(); return propertiesFactoryBean.getObject(); @Bean(name="scheduler") public Scheduler scheduler(){ return schedulerFactoryBean().getScheduler();}
MyJob
package com.wsy.quartz02.job;import lombok.extern.slf4j.Slf4j;import org.quartz.Job;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import org.springframework.stereotype.Component;import java.util.Date;@Component@Slf4jpublic class MyJob implements Job { @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { System.err.println("MyJob是一个空的任务计划,时间:"+new Date().toLocaleString()); }}
MyJob1
package com.wsy.quartz02.job;import lombok.extern.slf4j.Slf4j;import org.quartz.*;import org.springframework.stereotype.Component;import java.util.Date;@Component@Slf4jpublic class MyJob1 implements Job { @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { JobDetail jobDetail = jobExecutionContext.getJobDetail(); JobDataMap jobDataMap = jobDetail.getJobDataMap(); System.out.println(new Date().toLocaleString()+"-->携带参数个数:"+jobDataMap.size()); }}
MyJob2
package com.wsy.quartz02.job;import lombok.extern.slf4j.Slf4j;import org.quartz.*;import org.springframework.stereotype.Component;import java.util.Date;@Component@Slf4jpublic class MyJob2 implements Job { @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { JobDetail jobDetail = jobExecutionContext.getJobDetail(); JobDataMap jobDataMap = jobDetail.getJobDataMap(); System.out.println(new Date().toLocaleString()+"-->MyJob2参数传递name="+jobDataMap.get("name")+",score="+ jobDataMap.get("score")); }}
Quartz02Controller
package com.wsy.quartz02.controler;import com.wsy.quartz02.model.ScheduleTrigger;import com.wsy.quartz02.service.ScheduleTriggerService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;import java.util.List;@Controller@RequestMapping("/quartz")public class Quartz02Controller { @Autowired private ScheduleTriggerService scheduleTriggerService; @RequestMapping("/list") public ModelAndView getAll(){ ModelAndView mv = new ModelAndView(); List<ScheduleTrigger> list = scheduleTriggerService.queryScheduleTriggerLst(); mv.addObject("quartzList",list); mv.setViewName("index"); return mv; } @RequestMapping("/edit") public String editStatus(ScheduleTrigger scheduleTrigger){ int n = scheduleTriggerService.updateByPrimaryKeySelective(scheduleTrigger); return "redirect:/quartz/list"; } @RequestMapping("/proSave/{id}") public ModelAndView proSave(@PathVariable(value = "id") Integer id){ ModelAndView mv=new ModelAndView(); ScheduleTrigger scheduleTrigger = scheduleTriggerService.selectByPrimaryKey(id); mv.addObject("schedule",scheduleTrigger); mv.setViewName("edit"); return mv; }}
ScheduleTriggerService
package com.wsy.quartz02.service;import com.wsy.quartz02.model.ScheduleTrigger;import java.util.List; public interface ScheduleTriggerService { int deleteByPrimaryKey(Integer id); int insert(ScheduleTrigger record); int insertSelective(ScheduleTrigger record); ScheduleTrigger selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(ScheduleTrigger record); int updateByPrimaryKey(ScheduleTrigger record); List<ScheduleTrigger> queryScheduleTriggerLst();}
Quartz02Application
package com.wsy.quartz02;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.scheduling.annotation.EnableScheduling;import org.springframework.transaction.annotation.EnableTransactionManagement;@MapperScan("com.wsy.quartz02.mapper")@EnableTransactionManagement@EnableScheduling@SpringBootApplicationpublic class Quartz02Application { public static void main(String[] args) { SpringApplication.run(Quartz02Application.class, args); }}
界面
<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head> <meta charset="UTF-8"> <title>quartz定时任务管理</title></head><body><h2 >定时任务</h2><table align="center" border="1px" width="50%"> <tr> <td>id</td> <td>表达式</td> <td>状态</td> <td>工作类</td> <td>分组</td> <td>操作</td> </tr> <tr th:each="q : ${quartzList}"> <td th:text="${q.id}"></td> <td th:text="${q.cron}"></td> <td th:text="${q.status}"></td> <td th:text="${q.job_name}"></td> <td th:text="${q.job_group}"></td> <td th:switch ="${q.status} == 0"> <a th:case="true" th:href="@{/quartz/edit(id=${q.id},status=1)}" rel="external nofollow" >启动</a> <a th:case="false" th:href="@{/quartz/edit(id=${q.id},status=0)}" rel="external nofollow" >停止</a> <a th:href="@{'/quartz/proSave/'+${q.id}}" rel="external nofollow" >编辑</a> <a th:href="@{'/add/'}" rel="external nofollow" >增加</a> </td> </tr></table></body></html>
edit.html
<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head> <meta charset="UTF-8"> <title>修改定时任务</title></head><body><h2>修改定时任务</h2><form th:action="@{/quartz/edit}" method="post"> <input type="hidden" name="id" th:value="${schedule.id}" /> 表达式: <input width="300px" type="text" name="cron" th:value="${schedule.cron}" /></br> 工作类: <input width="300px" type="text" name="job_name" th:value="${schedule.job_name}" /></br> 分组:<input width="300px" type="text" name="job_group" th:value="${schedule.job_group}" /></br> <input type="submit" value="提交"/></form></body></html>
以上是“如何集合SpringBoot+Quartz+数据库存储”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注编程网行业资讯频道!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341