首页 > 作文

SpringBoot+Quartz+数据库存储的完美集合

更新时间:2023-04-05 02:01:16 阅读: 评论:0

官网: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&g2019年清明节t;                </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;imposubstringrt org.springframework.stereotype.component;/** * @author干的漂亮 * @site www.wangmage.com * @company 干得漂亮公司 * @create 2019 - 11-15 17:05 */@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;/*#============================================================================# jdbc#============================================================================org.quartz.jobstore.driverdelegateclass:org.quartz.impl.jdbcjobstore.stdjdbcdelegateorg.quartz.jobstore.uproperties:falorg.quartz.jobstore.datasource:qzds#org.quartz.datasource.qzds.connectionprovider.class:org.quartz.utils.poolingconnectionproviderorg.quartz.datasource.qzds.connectionprovider.class:com.zking.q03.quartz.druidconnectionproviderorg.quartz.datasource.qzds.driver:com.mysql.jdbc.driverorg.quartz.datasource.qzds.url:jdbc:mysql://127.0.0.1:3306/test?uunicode=true&characterencoding=utf-8org.quartz.datasource.qzds.ur:rootorg.quartz.datasource.qzds.password:rootorg.quartz.datasource.qzds.maxconnections:30org.quartz.datasource.qzds.validationquery: lect 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保持一致(去掉前缀),同时提供t方法,quartz框架自动注入值。     *     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     */    //jdbc驱动    public string driver;    //jdbc连接串    public string url;    //数据库用户名    public string ur;    //数据库用户密码    public string password;    //数据库最大连接数    public int maxconnection;    //数据库sql查询每次连接返回执行到连接池,以确保它仍然是有效的。    public string validationquery;    private boolean validateoncheckout;    private int idleconnectionvalidationconds;    public string maxcachedstatementsperconnection;    private string discardidleconnectionsconds;    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.clo();    }    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.tdriverclassname(this.driver);        } catch (exception e) {            try {                throw new schedulerexception("problem tting driver class name on datasource: " + e.getmessage(), e);            } catch (schedulerexception e1) {            }        }        datasource.turl(this.url);        datasource.turname(this.ur);        datasource.tpassword(this.password);        datasource.tmaxactive(this.maxconnection);        datasource.tminidle(1);        datasource.tmaxwait(0);        datasource.tmaxpoolpreparedstatementperconnectionsize(this.default_db_max_cached_statements_per_connection);        if (this.validationquery != null) {            datasource.tvalidationquery(this.validationquery);            if(!this.validateoncheckout)                datasource.ttestonreturn(true);            el                datasource.ttestonborrow(true);            datasource.tvalidationquerytimeout(this.idleconnectionvalidationconds);        }    }    /*     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     *     * 提供get t方法     *     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     */    public string getdriver() {        return driver;    }    public void tdriver(string driver) {        this.driver = driver;    }    public string geturl() {        return url;    }    public void turl(string url) {        this.url = url;    }    public string getur() {        return ur;    }    public void tur(string ur) {        this.ur = ur;    }    public string getpassword() {        return password;    }    public void tpassword(string password) {        this.password = password;    }    public int getmaxconnection() {        return maxconnection;    }    public void tmaxconnection(int maxconnection) {        this.maxconnection = maxconnection;    }    public string getvalidationquery() {        return validationquery;    }    public void tvalidationquery(string validationquery) {        this.validationquery = validationquery;    }    public boolean isvalidateoncheckout() {        return validateoncheckout;    }    public void tvalidateoncheckout(boolean validateoncheckout) {        this.validateoncheckout = validateoncheckout;    }    public int getidleconnectionvalidationconds() {        return idleconnectionvalidationconds;    }    public void tidleconnectionvalidationconds(int idleconnectionvalidationconds) {        this.idleconnectionvalidationconds = idleconnectionvalidationconds;    }    public druiddatasource getdatasource() {        return datasource;    }    public void tdatasource(druiddatasource datasource) {        this.datasource = datasource;    }}

application.yml

rver:  rvlet:    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?uunicode=true&characterencoding=utf8    urname: 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: lect 1 from dual      test-while-idle: true      test-on-borrow: true      test-on-return: fal      # 是否缓存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/*"        ssion-stat-enable: true        ssion-stat-max-count: 100      stat-view-rvlet:        enabled: true        url-pattern: /druid/*        ret-enable: true        #设置监控页面的登录名和密码        login-urname: admin        login-password: admin        allow: 127.0.0.1        #deny: 192.168.1.100#显示日志logging:  level:    com.wsy.quartz02.mapper: d白居易介绍ebug

quartz.properties

##============================================================================# configure main scheduler properties 调度器属性#============================================================================org.quartz.scheduler.instancename: defaultquartzschedulerorg.quartz.scheduler.instanceid = autoorg.quartz.scheduler.rmi.export: falorg.quartz.scheduler.rmi.proxy: falorg.quartz.scheduler.wrapjobexecutioninurtransaction: falorg.quartz.threadpool.class: org.quartz.simpl.simplethreadpoolorg.quartz.threadpool.threadcount= 10org.quartz.threadpool.threadpriority: 5org.quartz.threadpool.threadsinheritcontextclassloaderofinitializingthread: trueorg.quartz.jobstore.misfirethreshold: 60000#============================================================================# configure jobstore#============================================================================#存储方式使用jobstoretx,也就是数据库org.quartz.jobstore.class: org.quartz.impl.jdbcjobstore.jobstoretxorg.quartz.jobstore.driverdelegateclass:org.quartz.impl.jdbcjobstore.stdjdbcdelegate#使用自己的配置文件org.quartz.jobstore.uproperties: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.druidconnectionproviderorg.quartz.datasource.qzds.driver: com.mysql.jdbc.driverorg.quartz.datasource.qzds.url: jdbc:mysql://localhost:3306/mysql?uunicode=true&characterencoding=utf8org.quartz.datasource.qzds.ur: rootorg.quartz.datasource.qzds.password: 123org.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;@repositorypublic interface scheduletriggermapper {    int deletebyprimarykey(integer id);    int inrt(scheduletrigger record);    int inrtlective(scheduletrigger record);    scheduletrigger lectbyprimarykey(integer id);    int updatebyprimarykeylective(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;@repositorypublic interface scheduletriggerparammapper {    int deletebyprimarykey(integer param_id);    int inrt(scheduletriggerparam record);    int inrtlective(scheduletriggerparam record);    scheduletriggerparam lectbyprimarykey(integer param_id);    int updatebyprimarykeylective(scheduletriggerparam record);    int updatebyprimarykey(scheduletriggerparam record);    /**     * 查询出当前任务类对应所需的参数     * @param triggerid     * @return     */    list<scheduletriggerparam> queryscheduleparamlst(integer triggerid);}

scheduletriggerparam

<lect id="queryscheduleparamlst" resulttype="com.wsy.quartz02.model.scheduletriggerparam">    lect <include refid="ba_column_list"/>    from t_schedule_trigger_param where schedule_trigger_id=#{triggerid}  </lect>

scheduletrigger

<lect id="queryscheduletriggerlst" resulttype="com.wsy.quartz02.model.scheduletrigger">    lect <include refid="ba_column_list"/>    from t_schedule_trigger  </lect>

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.tquartzproperties(quartzproperties());                factorybean.tjobfactory(myjobfactory);                return factorybean;            } catch (ioexception e) {                throw new runtimeexception(e);            }    }    public properties quartzproperties() throws ioexception {        propertiesfactorybean propertiesfactorybean=new propertiesfactorybean();        propertiesfactorybean.tlocation(new classpathresource("/quartz.properties"));        propertiesfactorybean.afterpropertiest();        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.rvice.scheduletriggerrvice;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.rvlet.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 scheduletriggerrvice scheduletriggerrvice;    @requestmapping("/list")    public modelandview getall(){        modelandview mv = new modelandview();        list<scheduletrigger> list = scheduletriggerrvice.queryscheduletriggerlst();        mv.addobject("quartzlist",list);        mv.tviewname("index");        return mv;    }    @requestmapping("/edit")    public string editstatus(scheduletrigger scheduletrigger){        int n = scheduletriggerrvice.updatebyprimarykeylective(scheduletrigger);        return "redirect:/quartz/list";    }    @requestmapping("/prosave/{id}")    public modelandview prosave(@pathvariable(value = "id") integer id){        modelandview mv=new modelandview();        scheduletrigger scheduletrigger = scheduletriggerrvice.lectbyprimarykey(id);        mv.addobject("schedule",scheduletrigger);        mv.tviewname("edit");        return mv;    }}

scheduletriggerrvice

package com.wsy.quartz02.rvice;import com.wsy.quartz02.model.scheduletrigger;import java.util.list;/** * @author干的漂亮 * @site www.wangmage.com * @company 干得漂亮公司 * @create 2019 - 11-16 16:02 */ public interface scheduletriggerrvice {        int deletebyprimarykey(integer id);        int inrt(scheduletrigger record);        int inrtlective(scheduletrigger record);        scheduletrigger lectbyprimarykey(integer id);        int updatebyprimarykeylective(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@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 chart="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:ca="true" th:href="@{/quartz/edit(id=${q.id},status=1)}" rel="external nofollow" >启动</a>            <a th:ca="fal" 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 chart="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+数据库存储内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!

本文发布于:2023-04-05 02:01:12,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/45401cd55e14f19b16ba6412ce643d2c.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:SpringBoot+Quartz+数据库存储的完美集合.doc

本文 PDF 下载地址:SpringBoot+Quartz+数据库存储的完美集合.pdf

标签:数据库   漂亮   连接池   干得
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图