1. 程式人生 > >Spring Boot整合持久化Quartz定時任務管理和介面展示

Spring Boot整合持久化Quartz定時任務管理和介面展示

前言

本文是對之前的一篇文章Spring+SpringMVC+mybatis+Quartz整合程式碼部分做的一個修改和補充, 其中最大的變化就是後臺框架變成了Spring Boot。

本工程所用到的技術或工具有:

  • Spring Boot
  • Mybatis
  • Quartz
  • PageHelper
  • VueJS
  • ElementUI
  • MySql資料庫

正文

配置

本例中仍然是使用mysql資料庫作為Quartz任務持久化的儲存載體。對於如何在Mysql資料庫中建立表,在上一篇Spring+SpringMVC+mybatis+Quartz整合中已經有了詳細的介紹。這裡我們來看Spring Boot工程的建立方法。在

Spring網站上有關於建立Spring Boot工程的腳手架,我們按如下圖的方式設定,然後點選Generate Project即可。


這裡寫圖片描述

接著我們在IDE中匯入這個maven工程,然後可以看到src/main/resource下面有一個名字為application.properties的檔案,裡面的內容是空的。我們刪除這個檔案,然後在這個目錄下新建一個名為application.yml的檔案。這是配置Spring Boot工程的另一種方式,也是Spring Boot官方推薦的一種配置方式。我們在新建的這個yml檔案中,加入如下程式碼

spring:
  datasource:
    url: jdbc:mysql://190.0
.1.88:3306/hello_test?useUnicode=true username: root password: root driver-class-name: com.mysql.jdbc.Driver mybatis: mapper-locations: - classpath:com/example/demo/mapper/*.xml type-aliases-package: com.example.demo.entity

上面的程式碼是對資料庫和mybatis的一些配置。

接著我們在當前目錄下再新建一個名為quartz.properties的檔案。這是對Quartz的配置檔案。加入如下程式碼:

# 固定字首org.quartz
# 主要分為scheduler、threadPool、jobStore、plugin等部分
#
#
org.quartz.scheduler.instanceName = DefaultQuartzScheduler
org.quartz.scheduler.rmi.export = false
org.quartz.scheduler.rmi.proxy = false
org.quartz.scheduler.wrapJobExecutionInUserTransaction = false

# 例項化ThreadPool時,使用的執行緒類為SimpleThreadPool
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool

# threadCount和threadPriority將以setter的形式注入ThreadPool例項
# 併發個數
org.quartz.threadPool.threadCount = 5
# 優先順序
org.quartz.threadPool.threadPriority = 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true

org.quartz.jobStore.misfireThreshold = 5000

# 預設儲存在記憶體中
#org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore

#持久化
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX

org.quartz.jobStore.tablePrefix = QRTZ_

org.quartz.jobStore.dataSource = qzDS

org.quartz.dataSource.qzDS.driver = com.mysql.jdbc.Driver

org.quartz.dataSource.qzDS.URL = jdbc:mysql://190.0.1.88:3306/hello_test?useUnicode=true&characterEncoding=UTF-8

org.quartz.dataSource.qzDS.user = root

org.quartz.dataSource.qzDS.password = root

org.quartz.dataSource.qzDS.maxConnections = 10

可以看出和上一篇文章的配置檔案完成相同。接著我們在com.example.demo下新建一個名為SchedulerConfig.java的檔案。在這個檔案裡,對剛才我們新建的quartz.properties檔案進行讀取。

package com.example.demo;

import java.io.IOException;
import java.util.Properties;

import org.quartz.Scheduler;
import org.quartz.ee.servlet.QuartzInitializerListener;
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;

@Configuration
public class SchedulerConfig {

    @Bean(name="SchedulerFactory")
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setQuartzProperties(quartzProperties());
        return factory;
    }

    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        //在quartz.properties中的屬性被讀取並注入後再初始化物件
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }

    /*
     * quartz初始化監聽器
     */
    @Bean
    public QuartzInitializerListener executorListener() {
       return new QuartzInitializerListener();
    }

    /*
     * 通過SchedulerFactoryBean獲取Scheduler的例項
     */
    @Bean(name="Scheduler")
    public Scheduler scheduler() throws IOException {
        return schedulerFactoryBean().getScheduler();
    }

}

注意最下方的QuartzInitializerListener。在SpringMVC中,我們在配置Quartz的時候,要在web.xml中加入如下配置:

    <listener>
        <listener-class>
            org.quartz.ee.servlet.QuartzInitializerListener
        </listener-class>
    </listener>

這個監聽器可以監聽到工程的啟動,在工程停止再啟動時可以讓已有的定時任務繼續進行。由於我們目前的工程是Spring Boot,沒有web.xml的配置方式,所以我們在上文的SchedulerConfig類中直接注入了這個Bean。

實現

先來看Job類。首先設定一個BaseJob介面,用來繼承Job類:

package com.example.demo.job;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public interface BaseJob extends Job{
    public void execute(JobExecutionContext context) throws JobExecutionException;
}

然後兩個Job類用來實現BaseJob類:
HelloJob

package com.example.demo.job;

import java.util.Date;  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;   
import org.quartz.JobExecutionContext;  
import org.quartz.JobExecutionException;  

public class HelloJob implements BaseJob {  

    private static Logger _log = LoggerFactory.getLogger(HelloJob.class);  

    public HelloJob() {  

    }  

    public void execute(JobExecutionContext context)  
        throws JobExecutionException {  
        _log.error("Hello Job執行時間: " + new Date());  

    }  
}  

NewJob

package com.example.demo.job;

import java.util.Date;  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
import org.quartz.JobExecutionContext;  
import org.quartz.JobExecutionException;  

public class NewJob implements BaseJob {  

    private static Logger _log = LoggerFactory.getLogger(NewJob.class);  

    public NewJob() {  

    }  

    public void execute(JobExecutionContext context)  
        throws JobExecutionException {  
        _log.error("New Job執行時間: " + new Date());  

    }  
}  

至於這樣做的目的,我們可以先看一下Controller

package com.example.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.entity.JobAndTrigger;
import com.example.demo.job.BaseJob;
import com.example.demo.service.IJobAndTriggerService;
import com.github.pagehelper.PageInfo;


@RestController
@RequestMapping(value="/job")
public class JobController 
{
    @Autowired
    private IJobAndTriggerService iJobAndTriggerService;

    //加入Qulifier註解,通過名稱注入bean
    @Autowired @Qualifier("Scheduler")
    private Scheduler scheduler;

    private static Logger log = LoggerFactory.getLogger(JobController.class);  


    @PostMapping(value="/addjob")
    public void addjob(@RequestParam(value="jobClassName")String jobClassName, 
            @RequestParam(value="jobGroupName")String jobGroupName, 
            @RequestParam(value="cronExpression")String cronExpression) throws Exception
    {           
        addJob(jobClassName, jobGroupName, cronExpression);
    }

    public void addJob(String jobClassName, String jobGroupName, String cronExpression)throws Exception{

        // 啟動排程器  
        scheduler.start(); 

        //構建job資訊
        JobDetail jobDetail = JobBuilder.newJob(getClass(jobClassName).getClass()).withIdentity(jobClassName, jobGroupName).build();

        //表示式排程構建器(即任務執行的時間)
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);

        //按新的cronExpression表示式構建一個新的trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobClassName, jobGroupName)
            .withSchedule(scheduleBuilder).build();

        try {
            scheduler.scheduleJob(jobDetail, trigger);

        } catch (SchedulerException e) {
            System.out.println("建立定時任務失敗"+e);
            throw new Exception("建立定時任務失敗");
        }
    }


    @PostMapping(value="/pausejob")
    public void pausejob(@RequestParam(value="jobClassName")String jobClassName, @RequestParam(value="jobGroupName")String jobGroupName) throws Exception
    {           
        jobPause(jobClassName, jobGroupName);
    }

    public void jobPause(String jobClassName, String jobGroupName) throws Exception
    {   
        scheduler.pauseJob(JobKey.jobKey(jobClassName, jobGroupName));
    }


    @PostMapping(value="/resumejob")
    public void resumejob(@RequestParam(value="jobClassName")String jobClassName, @RequestParam(value="jobGroupName")String jobGroupName) throws Exception
    {           
        jobresume(jobClassName, jobGroupName);
    }

    public void jobresume(String jobClassName, String jobGroupName) throws Exception
    {
        scheduler.resumeJob(JobKey.jobKey(jobClassName, jobGroupName));
    }


    @PostMapping(value="/reschedulejob")
    public void rescheduleJob(@RequestParam(value="jobClassName")String jobClassName, 
            @RequestParam(value="jobGroupName")String jobGroupName,
            @RequestParam(value="cronExpression")String cronExpression) throws Exception
    {           
        jobreschedule(jobClassName, jobGroupName, cronExpression);
    }

    public void jobreschedule(String jobClassName, String jobGroupName, String cronExpression) throws Exception
    {               
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(jobClassName, jobGroupName);
            // 表示式排程構建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);

            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

            // 按新的cronExpression表示式重新構建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

            // 按新的trigger重新設定job執行
            scheduler.rescheduleJob(triggerKey, trigger);
        } catch (SchedulerException e) {
            System.out.println("更新定時任務失敗"+e);
            throw new Exception("更新定時任務失敗");
        }
    }


    @PostMapping(value="/deletejob")
    public void deletejob(@RequestParam(value="jobClassName")String jobClassName, @RequestParam(value="jobGroupName")String jobGroupName) throws Exception
    {           
        jobdelete(jobClassName, jobGroupName);
    }

    public void jobdelete(String jobClassName, String jobGroupName) throws Exception
    {       
        scheduler.pauseTrigger(TriggerKey.triggerKey(jobClassName, jobGroupName));
        scheduler.unscheduleJob(TriggerKey.triggerKey(jobClassName, jobGroupName));
        scheduler.deleteJob(JobKey.jobKey(jobClassName, jobGroupName));             
    }


    @GetMapping(value="/queryjob")
    public Map<String, Object> queryjob(@RequestParam(value="pageNum")Integer pageNum, @RequestParam(value="pageSize")Integer pageSize) 
    {           
        PageInfo<JobAndTrigger> jobAndTrigger = iJobAndTriggerService.getJobAndTriggerDetails(pageNum, pageSize);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("JobAndTrigger", jobAndTrigger);
        map.put("number", jobAndTrigger.getTotal());
        return map;
    }

    public static BaseJob getClass(String classname) throws Exception 
    {
        Class<?> class1 = Class.forName(classname);
        return (BaseJob)class1.newInstance();
    }


}

注意最下面的這個方法,根據類名稱,通過反射得到該類,然後建立一個BaseJob的例項。由於NewJob和HelloJob都實現了BaseJob,所以這裡不需要我們手動去判斷。這裡涉及到了一些java多型呼叫的機制,篇幅原因不多做解釋。

其他的部分,例如service層,dao層以及mapper,與上一篇文章幾乎完全相同。我們可以看一下現在的工程結構:


這裡寫圖片描述

我們可以看到static下的JobManager.html,這個是前端的一個簡單的管理頁面。Spring Boot的web工程中,靜態頁面可以放在static目錄下。這裡貼一下程式碼,與之前幾乎沒區別:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
    <title>QuartzDemo</title>
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/lib/theme-chalk/index.css">
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="http://cdn.bootcss.com/vue-resource/1.3.4/vue-resource.js"></script>
    <script src="https://unpkg.com/[email protected]/lib/index.js"></script>

    <style>      
      #top {
          background:#20A0FF;
          padding:5px;
          overflow:hidden
      }
    </style>

</head>
<body>
    <div id="test">             

        <div id="top">          
                <el-button type="text" @click="search" style="color:white">查詢</el-button>   
                <el-button type="text" @click="handleadd" style="color:white">新增</el-button>    
            </span>                     
        </div>  

        <br/>

        <div style="margin-top:15px">   

          <el-table
            ref="testTable"       
            :data="tableData"
            style="width:100%"
            border
            >
            <el-table-column
              prop="job_NAME"
              label="任務名稱"
              sortable
              show-overflow-tooltip>
            </el-table-column>

            <el-table-column
              prop="job_GROUP"
              label="任務所在組"
              sortable>
            </el-table-column>

            <el-table-column
              prop="job_CLASS_NAME"
              label="任務類名"
              sortable>
            </el-table-column>

            <el-table-column
              prop="trigger_NAME"
              label="觸發器名稱"
              sortable>
            </el-table-column>

            <el-table-column
              prop="trigger_GROUP"
              label="觸發器所在組"
              sortable>
            </el-table-column>

            <el-table-column
              prop="cron_EXPRESSION"
              label="表示式"
              sortable>
            </el-table-column>

            <el-table-column
              prop="time_ZONE_ID"
              label="時區"
              sortable>
            </el-table-column>

            <el-table-column label="操作" width="300">
              <template scope="scope">
                <el-button
                  size="small"
                  type="warning"
                  @click="handlePause(scope.$index, scope.row)">暫停</el-button>

                <el-button
                  size="small"
                  type="info"
                  @click="handleResume(scope.$index, scope.row)">恢復</el-button>

                <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)">刪除</el-button>

                <el-button
                  size="small"
                  type="success"
                  @click="handleUpdate(scope.$index, scope.row)">修改</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div align="center">
              <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="currentPage"
                  :page-sizes="[10, 20, 30, 40]"
                  :page-size="pagesize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="totalCount">
              </el-pagination>
          </div>
        </div> 

        <el-dialog title="新增任務" :visible.syn="dialogFormVisible">
          <el-form :model="form">
            <el-form-item label="任務名稱" label-width="120px" style="width:35%">
              <el-input v-model="form.jobName" auto-complete="off"></el-input>
            </el-form-item>     
            <el-form-item label="任務分組" label-width="120px" style="width:35%">
              <el-input v-model="form.jobGroup" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="表示式" label-width="120px" style="width:35%">
              <el-input v-model="form.cronExpression" auto-complete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="add">確 定</el-button>
          </div>
        </el-dialog>

        <el-dialog title="修改任務" :visible.syn="updateFormVisible">
          <el-form :model="updateform">
            <el-form-item label="表示式" label-width="120px" style="width:35%">
              <el-input v-model="updateform.cronExpression" auto-complete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="updateFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="update">確 定</el-button>
          </div>
        </el-dialog>

    </div>

    <footer align="center">
        <p>&copy; Quartz 任務管理</p>
    </footer>

    <script>
    var vue = new Vue({         
            el:"#test",
            data: {       
                //表格當前頁資料
                tableData: [],

                //請求的URL
                url:'job/queryjob',

                //預設每頁資料量
                pagesize: 10,               

                //當前頁碼
                currentPage: 1,

                //查詢的頁碼
                start: 1,

                //預設資料總數
                totalCount: 1000,

                //新增對話方塊預設可見性
                dialogFormVisible: false,

                //修改對話方塊預設可見性
                updateFormVisible: false,

                //提交的表單
                form: {
                    jobName: '',
                    jobGroup: '',
                    cronExpression: '',
                  },

                updateform: {
                    jobName: '',
                    jobGroup: '',
                    cronExpression: '',
                },
            },

            methods: {

                //從伺服器讀取資料
                loadData: function(pageNum, pageSize){                  
                    this.$http.get('job/queryjob?' + 'pageNum=' +  pageNum + '&pageSize=' + pageSize).then(function(res){
                        console.log(res)
                        this.tableData = res.body.JobAndTrigger.list;
                        this.totalCount = res.body.number;
                    },function(){
                        console.log('failed');
                    });                 
                },                              

                //單行刪除
                handleDelete: function(index, row) {
                    this.$http.post('job/deletejob',{"jobClassName":row.job_NAME,"jobGroupName":row.job_GROUP},{emulateJSON: true}).then(function(res){
                        this.loadData( this.currentPage, this.pagesize);
                    },function(){
                        console.log('failed');
                    });
                },

                //暫停任務
                handlePause: function(index, row){
                    this.$http.post('job/pausejob',{"jobClassName":row.job_NAME,"jobGroupName":row.job_GROUP},{emulateJSON: true}).then(function(res){
                        this.loadData( this.currentPage, this.pagesize);
                    },function(){
                        console.log('failed');
                    });
                },

                //恢復任務
                handleResume: function(index, row){
                    this.$http.post('job/resumejob',{"jobClassName":row.job_NAME,"jobGroupName":row.job_GROUP},{emulateJSON: true}).then(function(res){
                        this.loadData( this.currentPage, this.pagesize);
                    },function(){
                        console.log('failed');
                    });
                },

                //搜尋
                search: function(){
                    this.loadData(this.currentPage, this.pagesize);
                },

                //彈出對話方塊
                handleadd: function(){                      
                    this.dialogFormVisible = true;                
                },

                //新增
                add: function(){
                    this.$http.post('job/addjob',{"jobClassName":this.form.jobName,"jobGroupName":this.form.jobGroup,"cronExpression":this.form.cronExpression},{emulateJSON: true}).then(function(res){
                        this.loadData(this.currentPage, this.pagesize);
                        this.dialogFormVisible = false;
                    },function(){
                        console.log('failed');
                    });
                },

                //更新
                handleUpdate: function(index, row){
                    console.log(row)
                    this.updateFormVisible = true;
                    this.updateform.jobName = row.job_CLASS_NAME;
                    this.updateform.jobGroup = row.job_GROUP;
                },

                //更新任務
                update: function(){
                    this.$http.post
                    ('job/reschedulejob',
                            {"jobClassName":this.updateform.jobName,
                             "jobGroupName":this.updateform.jobGroup,
                             "cronExpression":this.updateform.cronExpression
                             },{emulateJSON: true}
                    ).then(function(res){
                        this.loadData(this.currentPage, this.pagesize);
                        this.updateFormVisible = false;
                    },function(){
                        console.log('failed');
                    });

                },

                //每頁顯示資料量變更
                handleSizeChange: function(val) {
                    this.pagesize = val;
                    this.loadData(this.currentPage, this.pagesize);
                },

                //頁碼變更
                handleCurrentChange: function(val) {
                    this.currentPage = val;
                    this.loadData(this.currentPage, this.pagesize);
                },        

            },      


          });

          //載入資料
          vue.loadData(vue.currentPage, vue.pagesize);
    </script>  

</body>
</html>

唯一的區別是這裡所用到的所有vue外掛和ElementUI外掛都是通過CDN方式引入,方便讀者下載之後直接執行。需要注意的是,在新增新的任務的時候,填寫任務名稱時一定要把這個Job類的完整路徑輸入進來。例如


這裡寫圖片描述

否則會報找不到該類的錯誤。對於Cron表示式,可以去線上Cron表示式生成器根據自己的需求自動生成。程式的截圖如下


這裡寫圖片描述

這兩個任務執行的log:

2017-06-27 17:23:56.194 ERROR 9972 --- [eduler_Worker-3] com.example.demo.job.HelloJob: Hello Job執行時間: Tue Jun 27 17:23:56 CST 2017
2017-06-27 17:23:57.042 ERROR 9972 --- [eduler_Worker-4] com.example.demo.job.NewJob: New Job執行時間: Tue Jun 27 17:23:57 CST 2017
2017-06-27 17:23:58.051 ERROR 9972 --- [eduler_Worker-5] com.example.demo.job.HelloJob: Hello Job執行時間: Tue Jun 27 17:23:58 CST 2017
2017-06-27 17:24:00.070 ERROR 9972 --- [eduler_Worker-1] com.example.demo.job.NewJob: New Job執行時間: Tue Jun 27 17:24:00 CST 2017
2017-06-27 17:24:00.144 ERROR 9972 --- [eduler_Worker-2] com.example.demo.job.HelloJob: Hello Job執行時間: Tue Jun 27 17:24:00 CST 2017
2017-06-27 17:24:02.099 ERROR 9972 --- [eduler_Worker-3] com.example.demo.job.HelloJob: Hello Job執行時間: Tue Jun 27 17:24:02 CST 2017
2017-06-27 17:24:0