SpringBoot+Quartz+数据库存储的完美集合
程序员文章站
2022-10-29 14:37:23
官网:http://www.quartz-scheduler.org/我们所需数据库pom依赖 spring-boot-starter-jdbc
官网: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>src/main/resources</directory> </resource> <!--解决mybatis-generator-maven-plugin运行时没有将xxxmapper.xml文件放入target文件夹的问题--> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题--> <resource> <directory>src/main/resources</directory> <includes> <include>*.properties</include> <include>*.xml</include> <include>*.yml</include> </includes> </resource> </resources> <plugins> <plugin> <groupid>org.mybatis.generator</groupid> <artifactid>mybatis-generator-maven-plugin</artifactid> <version>1.3.2</version> <dependencies> <!--使用mybatis-generator插件不能使用太高版本的mysql驱动 --> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <version>${mysql.version}</version> </dependency> </dependencies> <configuration> <overwrite>true</overwrite> </configuration> </plugin> <plugin> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-maven-plugin</artifactid> </plugin> </plugins> </build> </project>
quartz默认的连接池是c3p0,如果你的连接池不同需要直接替换它的配置文件,比如我用的连接池是druid,就需要自己改配置(如果就用c3p0就不需要改) 工具类 utils myjobfactory
package com.wsy.quartz02.utils; import lombok.extern.slf4j.slf4j; import org.quartz.spi.triggerfiredbundle; import org.springframework.beans.factory.annotation.autowired; import org.springframework.beans.factory.config.autowirecapablebeanfactory; import org.springframework.scheduling.quartz.adaptablejobfactory; import org.springframework.stereotype.component; /** * @author干的漂亮 * @site www.wangmage.com * @company 干得漂亮公司 * @create 2019 - 11-15 17:05 */ @component @slf4j public 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; /* #============================================================================ # jdbc #============================================================================ org.quartz.jobstore.driverdelegateclass:org.quartz.impl.jdbcjobstore.stdjdbcdelegate org.quartz.jobstore.useproperties:false org.quartz.jobstore.datasource:qzds #org.quartz.datasource.qzds.connectionprovider.class:org.quartz.utils.poolingconnectionprovider org.quartz.datasource.qzds.connectionprovider.class:com.zking.q03.quartz.druidconnectionprovider org.quartz.datasource.qzds.driver:com.mysql.jdbc.driver org.quartz.datasource.qzds.url:jdbc:mysql://127.0.0.1:3306/test?useunicode=true&characterencoding=utf-8 org.quartz.datasource.qzds.user:root org.quartz.datasource.qzds.password:root org.quartz.datasource.qzds.maxconnections:30 org.quartz.datasource.qzds.validationquery: select 0 */ /** * @author干的漂亮 * @site www.wangmage.com * @company 干得漂亮公司 * @create 2019 - 11-15 17:02 */ /** * [druid连接池的quartz扩展类] * * @projectname: [] * @author: [xuguang] * @createdate: [2015/11/10 17:58] * @update: [说明本次修改内容] by[xuguang][2015/11/10] * @version: [v1.0] */ public class druidconnectionprovider implements connectionprovider { /* * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * 常量配置,与quartz.properties文件的key保持一致(去掉前缀),同时提供set方法,quartz框架自动注入值。 * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ //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); } } /* * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * 提供get set方法 * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ 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: 80 spring: 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: /* #设置不统计哪些url exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" session-stat-enable: true session-stat-max-count: 100 stat-view-servlet: enabled: true url-pattern: /druid/* reset-enable: true #设置监控页面的登录名和密码 login-username: admin login-password: admin allow: 127.0.0.1 #deny: 192.168.1.100 #显示日志 logging: level: com.wsy.quartz02.mapper: debug
quartz.properties
# #============================================================================ # configure main scheduler properties 调度器属性 #============================================================================ org.quartz.scheduler.instancename: defaultquartzscheduler org.quartz.scheduler.instanceid = auto org.quartz.scheduler.rmi.export: false org.quartz.scheduler.rmi.proxy: false org.quartz.scheduler.wrapjobexecutioninusertransaction: false org.quartz.threadpool.class: org.quartz.simpl.simplethreadpool org.quartz.threadpool.threadcount= 10 org.quartz.threadpool.threadpriority: 5 org.quartz.threadpool.threadsinheritcontextclassloaderofinitializingthread: true org.quartz.jobstore.misfirethreshold: 60000 #============================================================================ # configure jobstore #============================================================================ #存储方式使用jobstoretx,也就是数据库 org.quartz.jobstore.class: org.quartz.impl.jdbcjobstore.jobstoretx org.quartz.jobstore.driverdelegateclass:org.quartz.impl.jdbcjobstore.stdjdbcdelegate #使用自己的配置文件 org.quartz.jobstore.useproperties:true #数据库中quartz表的表名前缀 org.quartz.jobstore.tableprefix:qrtz_ org.quartz.jobstore.datasource:qzds #是否使用集群(如果项目只部署到 一台服务器,就不用了) org.quartz.jobstore.isclustered = true #============================================================================ # configure datasources #============================================================================ #配置数据库源(org.quartz.datasource.qzds.maxconnections: c3p0配置的是有s的,druid数据源没有s) org.quartz.datasource.qzds.connectionprovider.class:com.wsy.quartz02.utils.druidconnectionprovider org.quartz.datasource.qzds.driver: com.mysql.jdbc.driver org.quartz.datasource.qzds.url: jdbc:mysql://localhost:3306/mysql?useunicode=true&characterencoding=utf8 org.quartz.datasource.qzds.user: root org.quartz.datasource.qzds.password: 123 org.quartz.datasource.qzds.maxconnection: 10
scheduletriggermapper
package com.wsy.quartz02.mapper; import com.wsy.quartz02.model.scheduletrigger; import org.springframework.stereotype.repository; import java.util.list; @repository public interface scheduletriggermapper { int deletebyprimarykey(integer id); int insert(scheduletrigger record); int insertselective(scheduletrigger record); scheduletrigger selectbyprimarykey(integer id); int updatebyprimarykeyselective(scheduletrigger record); int updatebyprimarykey(scheduletrigger record); /** * 查询触发器中包含的所有任务 * @return */ list<scheduletrigger> queryscheduletriggerlst(); }
scheduletriggerparammapper
package com.wsy.quartz02.mapper; import com.wsy.quartz02.model.scheduletriggerparam; import org.springframework.stereotype.repository; import java.util.list; @repository public 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); /** * 查询出当前任务类对应所需的参数 * @param triggerid * @return */ 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; @configuration public 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 @slf4j public 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 @slf4j public 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 @slf4j public 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; /** * @author干的漂亮 * @site www.wangmage.com * @company 干得漂亮公司 * @create 2019 - 11-16 16:02 */ @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; /** * @author干的漂亮 * @site www.wangmage.com * @company 干得漂亮公司 * @create 2019 - 11-16 16:02 */ 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); /** * 查询触发器中包含的所有任务 * @return */ 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 @springbootapplication public 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> <h1 style="text-align: center">定时任务</h1> <table style="text-align: center" 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> <h1>修改定时任务</h1> <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+数据库存储的文章就介绍到这了,更多相关springboot+quartz+数据库存储内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: 跨域和CORS
推荐阅读
-
通过系统数据库获取用户所有数据库中的视图、表、存储过程
-
查询Sqlserver数据库死锁的一个存储过程分享
-
python使用adbapi实现MySQL数据库的异步存储
-
MySQL数据库的使用优势、数据库类型、常用的属性约束和常用存储引擎介绍
-
android之存储篇_SQLite数据库_让你彻底学会SQLite的使用
-
一个查看MSSQLServer数据库空间使用情况的存储过程 SpaceUsed
-
SQL server 数据库的索引和视图、存储过程和触发器
-
Oracle中 关于数据库存储过程和存储函数的使用
-
Windows 64位下装安装Oracle 11g,PLSQL Developer的配置问题,数据库显示空白的完美解决方案(图文教程)
-
PHP将session信息存储到数据库的类实例