Spring boot XXL-JOB使用方法

1.在想要不要介紹呢,哈哈哈哈

XXL-JOB就相當于一個動態(tài)的定時任務,可以動態(tài)的去修改任務,啟動任務/停止任務,以及終止任務。但是不能動態(tài)的去創(chuàng)建定時任務,只能去調(diào)度中心去添加任務,嘿嘿不過我們可以通過 代碼直接訪問調(diào)度中心的接口然后創(chuàng)建定時任務。

寂寞啊

2.下面我們正式開始

2.1 首先XXL-JOB的官網(wǎng)地址是:https://www.xuxueli.com/xxl-job/,可以去看看官方文檔,比較更加的清楚。
2.2 我們需要下載XXL-JOB的源碼,下載地址是:
| https://github.com/xuxueli/xxl-job | Download |
| http://gitee.com/xuxueli0323/xxl-job | Download |
2.3 環(huán)境支持:
Maven3+
Jdk1.8+
Mysql5.7+
2.4 初始化“調(diào)度數(shù)據(jù)庫”
下載好XXL-JOB的源碼,解壓這個項目源碼,并獲取“調(diào)度數(shù)據(jù)庫初始化SQL腳本”,到mysql里面運行sql腳本文件,“調(diào)度數(shù)據(jù)庫SQL腳本”位置是:/xxl-job/doc/db/tables_xxl_job.sql
2.5 項目源碼結構:

xxl-job-admin:調(diào)度中心
xxl-job-core:公共依賴
xxl-job-executor-samples:執(zhí)行器Sample示例(選擇合適的版本執(zhí)行器,可直接使用,也可以參考其并將現(xiàn)有項目改造成執(zhí)行器)
:xxl-job-executor-sample-springboot:Springboot版本,通過Springboot管理執(zhí)行器,推薦這種方式;
:xxl-job-executor-sample-spring:Spring版本,通過Spring容器管理執(zhí)行器,比較通用;
:xxl-job-executor-sample-frameless:無框架版本;
:xxl-job-executor-sample-jfinal:JFinal版本,通過JFinal管理執(zhí)行器;
:xxl-job-executor-sample-nutz:Nutz版本,通過Nutz管理執(zhí)行器;
:xxl-job-executor-sample-jboot:jboot版本,通過jboot管理執(zhí)行器;

2.6 配置部署“調(diào)度中心”:

1.調(diào)度中心配置文件地址:/xxl-job/xxl-job admin/src/main/resources/application.properties。

2調(diào)度中心配置內(nèi)容說明:

調(diào)度中心JDBC鏈接:鏈接地址請保持和 2.1章節(jié) 所創(chuàng)建的調(diào)度數(shù)據(jù)庫的地址一致

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/xxl_job?Unicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root_pwd
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

報警郵箱

spring.mail.host=smtp.qq.com
spring.mail.port=25
spring.mail.username=xxx@qq.com
spring.mail.password=xxx
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory

調(diào)度中心通訊TOKEN [選填]:非空時啟用;

xxl.job.accessToken=

調(diào)度中心國際化配置 [必填]: 默認為 "zh_CN"/中文簡體, 可選范圍為 "zh_CN"/中文簡體, >"zh_TC"/中文繁體 and "en"/英文;

xxl.job.i18n=zh_CN

調(diào)度線程池最大線程配置【必填】

xxl.job.triggerpool.fast.max=200
xxl.job.triggerpool.slow.max=100

調(diào)度中心日志表數(shù)據(jù)保存天數(shù) [必填]:過期日志自動清理;限制大于等于7時生效,否則, 如-1,關閉自動清理功能;xxl.job.logretentiondays=30

按照上面的來配置完成以后,將項目編譯打包。

window如何打包并運行的:
SpringBoot打包成jar:

image.png

項目目錄多了個target文件夾,里面有剛才打包的jar文件,運行cmd,到target這個文件夾里面,直接:java -jar 打包的文件名字.jar,就可以直接運行了,如果不會用cmd到target這個文件夾里面,直接在打開這個target這個文件夾然后在
image.png
輸入cmd就可以了。網(wǎng)址:輸入:http://localhost:8080/xxl-job-admin/jobinfo,就可以進去了。
image.png

2.7 項目使用XXL-JOB步驟:

1.下面開始使用自己的項目然后調(diào)用XXL-JOB里面的調(diào)度中心,maven依賴,在pom.xml文件中引用xxl-job-core,示例圖:
image.png
<dependency>
  <groupId>com.xuxueli</groupId>
  <artifactId>xxl-job-core</artifactId>
  <version>2.2.0</version>
</dependency>

這里使用的是2.2.0版本。

2.配置文件
2.1.寫配置文件的數(shù)據(jù),在application.yml里面,如:

xxl:
  job:
    admin:
      addresses: http://localhost:8080/xxl-job-admin/jobinfo #任務管理器地址
      userName: admin #賬戶
      password: 123456 #密碼
      ifRemember: on #
    executor:
      appname: xxl-job-executor-sample #執(zhí)行器的AppName名字
      ip: ""#默認為空
      port: 9999
      logpath: data/applogs/xxl-job/jobhandler
      accessToken: 1111 #驗證,在調(diào)度中心中設置了,所以這邊也要設置,必須一樣
      logretentiondays: 30
      address:
      #注意:配置執(zhí)行器的名稱、IP地址、端口號,后面如果配置多個執(zhí)行器時,要防止端口沖突

2.2 添加配置文件XxlJobConfig.java

import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * xxl-job config
 *
 * @author xuxueli 2017-04-28
 */
@Configuration
public class XxlJobConfig {
    private Logger logger = LoggerFactory.getLogger(XxlJobConfig.class);

    @Value("${xxl.job.admin.addresses}")
    private String adminAddresses;

    @Value("${xxl.job.executor.accessToken}")
    private String accessToken;

    @Value("${xxl.job.executor.appname}")
    private String appname;

    @Value("${xxl.job.executor.address}")
    private String address;

    @Value("${xxl.job.executor.ip}")
    private String ip;

    @Value("${xxl.job.executor.port}")
    private int port;

    @Value("${xxl.job.executor.logpath}")
    private String logPath;

    @Value("${xxl.job.executor.logretentiondays}")
    private int logRetentionDays;


    @Bean
    public XxlJobSpringExecutor xxlJobExecutor() {
        logger.info(">>>>>>>>>>> xxl-job config init.");
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
        xxlJobSpringExecutor.setAppname(appname);
        xxlJobSpringExecutor.setAddress(address);
        xxlJobSpringExecutor.setIp(ip);
        xxlJobSpringExecutor.setPort(port);
        xxlJobSpringExecutor.setAccessToken(accessToken);
        xxlJobSpringExecutor.setLogPath(logPath);
        xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays);

        return xxlJobSpringExecutor;
    }
}

/**
 * 針對多網(wǎng)卡、容器內(nèi)部署等情況,可借助 "spring-cloud-commons" 提供的 "InetUtils" 組件靈活定制注冊IP;
 *
 *      1、引入依賴:
 *          <dependency>
 *             <groupId>org.springframework.cloud</groupId>
 *             <artifactId>spring-cloud-commons</artifactId>
 *             <version>${version}</version>
 *         </dependency>
 *
 *      2、配置文件,或者容器啟動變量
 *          spring.cloud.inetutils.preferred-networks: 'xxx.xxx.xxx.'
 *
 *      3、獲取IP
 *          String ip_ = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
 */
  1. 在項目中創(chuàng)建任務
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import groovy.util.logging.Slf4j;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class TestHandler {
     //calendarTest這個名字是你在添加定時任務的時候所需要的,他相當于指定這個定時任務執(zhí)行的是哪一個
    @XxlJob("calendarTest")
    public ReturnT<String> calendarTest(String param) throws Exception {
        //輸出你所傳的值
        System.out.println(param);
        return ReturnT.SUCCESS;
    }
}

  1. 在調(diào)度中心中添加執(zhí)行器


    image.png

    //注意:那個機器地址:是指的是你的ip地址,加上你在你項目里面添加的端口號,因為你啟動項目的時候他會在你項目里面在啟動一個端口,那個端口,就是你所需要的端口。

5.在調(diào)度中心中添加定時任務
image.png

然后點擊操作,選擇啟動
image.png
就可以看到了,對了,你必須要先把你的那個項目啟動,然后在點擊啟動。然后去調(diào)度日志里面可以查看到是否啟動成功了。

6.動態(tài)添加定時任務:
我們可以通過httpClinet 直接調(diào)用任務新增接口,動態(tài)添加任務,但是有一個前提,xxl-job-admin增加了登錄鑒權,任務的CRUD接口需要登錄信息,所以我們要先登錄才能調(diào)用接口。登錄代碼示例如下:

    private String cookie;
    //你部署的調(diào)度中心接口地址
    private String url = "http://localhost:8080/xxl-job-admin/jobinfo";
    //賬戶
    private String userName = "admin";
    //密碼
    private String password = "123456";
    //
    private String ifRemember = "on";
    //執(zhí)行器的id
    private int jobGroup = 1;
    //ps:或者你可以把這些放到配置文件中
    /**
     * 登錄
     * @return
     */
    private String getCookie() {
        String path = url + "/login";
        Map<String, Object> hashMap = new HashMap();
        hashMap.put("userName", userName);
        hashMap.put("password", password);
        hashMap.put("ifRemember", ifRemember);
        HttpResponse response = HttpRequest.post(path).form(hashMap).execute();
        List<HttpCookie> cookies = response.getCookies();
        StringBuilder sb = new StringBuilder();
        for (HttpCookie cookie : cookies) {
            sb.append(cookie.toString());
        }
        String cookie = sb.toString();
        return cookie;
    }
    /**
     * 添加任務,返回任務id
     * @param jobInfo
     * @return
     */
    public int addXxlJob(XxlJobInfo jobInfo){
        String path = url+ "/jobinfo/add";
        if (StringUtils.isBlank(cookie)) {
            cookie = getCookie();
        }
        jobInfo.setJobGroup(jobGroup);
        jobInfo.setExecutorRouteStrategy("FIRST");
        jobInfo.setGlueType(GlueTypeEnum.BEAN.name());
        jobInfo.setExecutorBlockStrategy(ExecutorBlockStrategyEnum.SERIAL_EXECUTION.name());
        jobInfo.setExecutorTimeout(0);
        jobInfo.setExecutorFailRetryCount(0);
        jobInfo.setGlueRemark("GLUE代碼初始化");
        jobInfo.setAuthor("創(chuàng)建任務人的名稱");
        jobInfo.setAlarmEmail("你的郵箱");
        HttpResponse response = HttpRequest.post(path).form(JSON.parseObject(JSON.toJSONString(jobInfo),Map.class)).execute();
        if (HttpStatus.HTTP_OK != response.getStatus()) {
            // TODO
            throw new LogicException("請求失敗");
        }
        JSONObject jsonObject = JSON.parseObject(response.body());
        if(HttpStatus.HTTP_OK != jsonObject.getIntValue("code")){
            throw new LogicException("添加失敗,"+jsonObject.getIntValue("msg"));
        }
        int jobId = jsonObject.getIntValue("content");
        return jobId;
    }

    /**
     * 刪除任務
     * @param id
     */
    public boolean  deleteXxlJob(int id){
        String path = url+ "/jobinfo/remove";
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("id", id);
        if (StringUtils.isBlank(cookie)) {
            cookie = getCookie();
        }
        HttpResponse response = HttpRequest.post(path).form(paramMap).execute();
        if (HttpStatus.HTTP_OK != response.getStatus()) {
            // TODO
            throw new LogicException("請求失敗");
        }
        JSONObject jsonObject = JSON.parseObject(response.body());
        if(HttpStatus.HTTP_OK != jsonObject.getIntValue("code")){
            throw new LogicException("刪除失敗,"+jsonObject.getIntValue("msg"));
        }
        return true;
    }

    /**
     * 修改任務
     * @param jobInfo
     * @return
     */
    public boolean updateXxlJob(XxlJobInfo jobInfo){
        String path = url+ "/jobinfo/update";
        if (StringUtils.isBlank(cookie)) {
            cookie = getCookie();
        }
        HttpResponse response = HttpRequest.post(path).form(JSON.parseObject(JSON.toJSONString(jobInfo),Map.class)).execute();
        if (HttpStatus.HTTP_OK != response.getStatus()) {
            // TODO
            throw new LogicException("請求失敗");
        }
        JSONObject jsonObject = JSON.parseObject(response.body());
        if(HttpStatus.HTTP_OK != jsonObject.getIntValue("code")){
            throw new LogicException("修改失敗,"+jsonObject.getIntValue("msg"));
        }
        return true;
    }
    /**
     * 啟動任務
     * @param id
     * @return
     */
    public  boolean stopXxlJob(int id){
        String path = url+ "/jobinfo/start";
        if (StringUtils.isBlank(cookie)) {
            cookie = getCookie();
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("id", id);
        HttpResponse response = HttpRequest.post(path).form(paramMap).execute();
        if (HttpStatus.HTTP_OK != response.getStatus()) {
            // TODO
            throw new LogicException("請求失敗");
        }
        JSONObject jsonObject = JSON.parseObject(response.body());
        if(HttpStatus.HTTP_OK != jsonObject.getIntValue("code")){
            throw new LogicException("啟動失敗,"+jsonObject.getIntValue("msg"));
        }
        return true;
    }
    /**
     * 停止任務
     * @param id
     * @return
     */
    public boolean puseXxlJob(int id){
        String path = url+ "/jobinfo/stop";
        if (StringUtils.isBlank(cookie)) {
            cookie = getCookie();
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("id", id);
        HttpResponse response = HttpRequest.post(path).form(paramMap).execute();
        if (HttpStatus.HTTP_OK != response.getStatus()) {
            // TODO
            throw new LogicException("請求失敗");
        }
        JSONObject jsonObject = JSON.parseObject(response.body());
        if(HttpStatus.HTTP_OK != jsonObject.getIntValue("code")){
            throw new LogicException("停止失敗,"+jsonObject.getIntValue("msg"));
        }
        return true;
    }

    /**
     * 根據(jù)id來查詢數(shù)據(jù)
     * @param id
     * @return
     */
    public XxlJobInfo getXxlJob(int id){
        String path = url+ "/jobinfo/get";
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("id", id);
        if (StringUtils.isBlank(cookie)) {
            cookie = getCookie();
        }
        HttpResponse response = HttpRequest.post(path).form(paramMap).execute();
        if (HttpStatus.HTTP_OK != response.getStatus()) {
            // TODO
            throw new LogicException("請求失敗");
        }
        JSONObject jsonObject = JSON.parseObject(response.body());
        if(HttpStatus.HTTP_OK != jsonObject.getIntValue("code")){
            throw new LogicException("查詢失敗,"+jsonObject.getIntValue("msg"));
        }
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.convertValue(jsonObject.get("data"),XxlJobInfo.class);
    }

下面在方法中調(diào)用這些接口吧:

1.新增:
public boolean inserCalendar() {
        HttpClinet httpClinet = new HttpClinet();     
        //添加任務
        XxlJobInfo xxlJobInfo = new XxlJobInfo();
        //描述
        xxlJobInfo.setJobDesc(“描述”);
        //執(zhí)行器,任務Handler名稱
        xxlJobInfo.setExecutorHandler("calendarTest");
        xxlJobInfo.setJobCron(“cron表達式”);
        //任務參數(shù)
        xxlJobInfo.setExecutorParam(1);
       //添加定時任務,返回定時任務id
        int jobId = httpClinet.addXxlJob(xxlJobInfo);
        return true;
    }
1.修改:
public boolean updateCalendar() {
        HttpClinet httpClinet = new HttpClinet();
        //查詢定時任務信息
        XxlJobInfo xxlJobInfo = httpClinet.getXxlJob("定時任務id");
        xxlJobInfo.setJobDesc(“描述”);
        xxlJobInfo.setJobCron(“Cron表達式”);
        httpClinet.updateXxlJob(xxlJobInfo);
        return true;
    }
     #轉(zhuǎn)換Cron表達式方法
     /**
     * 轉(zhuǎn)換
     * @param date
     * @param dateFormat  e.g:yyyy-MM-dd HH:mm:ss
     * @return
     */
    private static String formatDateByPattern(Date date, String dateFormat){
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        String formatTimeStr = null;
        if (date != null ) {
            formatTimeStr = sdf.format(date);
        }
        return formatTimeStr;
    }
     #String轉(zhuǎn)換Date方法
    /**
     * 轉(zhuǎn)換 時間
     * @param reminderTime 時間
   * @param pattern 格式y(tǒng)yyy-MM-dd HH:mm:ss
     * @return
     */
    public static Date transFormaTionData(String reminderTime, String pattern)  {

        try{
            SimpleDateFormat dateformat = new SimpleDateFormat(pattern);
            return dateformat.parse(reminderTime);
        }catch (ParseException e) {
            e.printStackTrace();
        }
        throw new LogicException("轉(zhuǎn)換時間出現(xiàn)問題");
    }
     #調(diào)用轉(zhuǎn)換Cron表達式方法
    /**
     * 獲取cron表達式
     * @param dateTime 時間2020-11-11 14:50:21
     * @return 21 50 14 11 11 ? 2020
     */
    private String jobCrons(String dateTime){
        String crons = formatDateByPattern("ss mm HH dd MM ? yyyy",transFormaTionData(dateTime,"yyyy-MM-dd HH:mm:ss"));
        return crons;
    }
       /**
     * 獲取月
     * @param dateTime
     * @return
     */
    public static int obtainMonth(String dateTime){
        try{
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date tmpDate = format.parse(dateTime);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(tmpDate);
            return (calendar.get(Calendar.MONTH) + 1);
        }catch (ParseException e){
            e.printStackTrace();
        }
        throw new LogicException("獲取月份出現(xiàn)問題");
    }
    /**
     * 獲取周
     */
    public static int obtainWeek(String dateTime){
        try{
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date tmpDate = format.parse(dateTime);
            Calendar cal = Calendar.getInstance();
            cal.setTime(tmpDate);
            return cal.get(Calendar.DAY_OF_WEEK);
        }catch (ParseException e){
            e.printStackTrace();
        }
        throw new LogicException("獲取周出現(xiàn)問題");
    }
    /**
     * 獲取第幾周
     * @param dateTime 時間
     * @return
     */
    public static int obtainWhatWeek(String dateTime){
        try{
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date tmpDate = format.parse(dateTime);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(tmpDate);
            return calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH);
        }catch (ParseException e){
            e.printStackTrace();
        }
        throw new LogicException("獲取月份出現(xiàn)問題");
    }
    /**
     * 轉(zhuǎn)換周
     * @param dayoFweek
     * @return
     */
    public static  String transFormaTionWeek(int dayoFweek){
        switch (dayoFweek){
            case 1:
                return "SUN";
            case 2:
                return "MON";
            case 3:
                return "TUE";
            case 4:
                return "WED";
            case 5:
                return "THU";
            case 6:
                return "FRI";
            case 7:
                return "SAT";
            default:
                break;
        }
        throw new LogicException("轉(zhuǎn)換周出現(xiàn)了問題");
    }
 /**
     * 重復時間段
     * @param repeatTime 0-不重復,1-每天重復,2每周重復,3-每月重復,4-每年重復,5-工作日重復
     * @param reminderTime 提前多少分鐘提醒
     * @param startDate 開始日期
     * @return
     */
    private String cron(Integer repeatTime, String reminderTime,String startDate){
        switch(repeatTime){
            case 1:
                //每天
                return formatDateByPattern("ss mm HH * * ?",transFormaTionData(reminderTime,"hh:mm"));
            case 2:
                //每周
                return formatDateByPattern("ss mm HH ? * "+transFormaTionWeek(obtainWeek(startDate)),transFormaTionData(reminderTime,"hh:mm"));
            case 3:
                //每月
                return formatDateByPattern("ss mm HH ? * "+obtainWeek(startDate)+"#"+obtainWhatWeek(startDate)+"",transFormaTionData(reminderTime,"hh:mm"));
            case 4:
                //每年
                return formatDateByPattern("ss mm HH ? "+obtainMonth(startDate)+" "+transFormaTionWeek(obtainWeek(startDate))+"",transFormaTionData(reminderTime,"hh:mm"));
            case 5:
                //工作日
                return formatDateByPattern("ss mm HH ? * MON-FRI",transFormaTionData(reminderTime,"hh:mm"));
                default:
                    return null;
        }
    }
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容