SpringBoot教程(二十三) | SpringBoot实现分布式定时任务之xxl-job

SpringBoot教程(二十三) | SpringBoot实现分布式定时任务之xxl-job

  • 简介
  • 一、前置条件:需要搭建调度中心
    • 1、先下载调度中心源码
    • 2、修改配置文件
    • 3、启动项目
    • 4、进行访问
    • 5、打包部署(上正式)
  • 二、SpringBoot集成Xxl-Job
    • 1. 引入xxl-job的依赖
    • 2. 在application.yml加上xxljob的配置
    • 3. 添加配置类
    • 4. 添加xxl-job测试(由调度中心进行测试)
      • 1.先在自己的Springboot项目中创建测试类
      • 2. 再进入已经启动成功的调度中心页面中进行操作
    • 5. 动态API调度任务 (看个人需求)
      • 在 xxl-job-admin 项目中
        • 1. 新建 MyDynamicApiController
        • 2. 创建 XxlJobQuery
      • 在 自己的 SpringBoot 项目中
        • 加maven依赖
        • 1.创建 XxlJobInfo 类
        • 2.创建 XxlJobUtil 类
        • 3. 创建 XxlJobController 进行测试

参考文章
【1】SpringBoot集成XxlJob分布式任务调度中心(超详细之手把手教学)
【2】搭建部署xxl-job调度中心详细过程
【3】springboot整合xxl-job项目使用(含完整代码)
【4】Springboot 整合 xxljob 动态API调度任务(进阶篇)

简介

XXL-JOB是一个分布式任务调度平台,其核心设计目标是开发迅速、学习简单、轻量级、易扩展。现已开放源代码并接入多家公司线上产品线,开箱即用。

一、前置条件:需要搭建调度中心

调度中心控制台页面,对所有的定时任务进行统一配置管理(配置执行器,配置任务,管理任务)

1、先下载调度中心源码

下载调度中心源码

github仓库地址: https://github.com/xuxueli/xxl-job
gitee仓库地址: http://gitee.com/xuxueli0323/xxl-job

我这边使用的是gitee上的master分支
使用idea拉取代码后,在xxl-job\doc\db的位置下存在一个tables_xxl_job.sql(初始化数据库sql脚本),将它导入数据库(默认使用的是mysql)
在这里插入图片描述

#
# XXL-JOB v2.4.2-SNAPSHOT
# Copyright (c) 2015-present, xuxueli.CREATE database if NOT EXISTS `xxl_job` default character set utf8mb4 collate utf8mb4_unicode_ci;
use `xxl_job`;SET NAMES utf8mb4;CREATE TABLE `xxl_job_info` (`id` int(11) NOT NULL AUTO_INCREMENT,`job_group` int(11) NOT NULL COMMENT '执行器主键ID',`job_desc` varchar(255) NOT NULL,`add_time` datetime DEFAULT NULL,`update_time` datetime DEFAULT NULL,`author` varchar(64) DEFAULT NULL COMMENT '作者',`alarm_email` varchar(255) DEFAULT NULL COMMENT '报警邮件',`schedule_type` varchar(50) NOT NULL DEFAULT 'NONE' COMMENT '调度类型',`schedule_conf` varchar(128) DEFAULT NULL COMMENT '调度配置,值含义取决于调度类型',`misfire_strategy` varchar(50) NOT NULL DEFAULT 'DO_NOTHING' COMMENT '调度过期策略',`executor_route_strategy` varchar(50) DEFAULT NULL COMMENT '执行器路由策略',`executor_handler` varchar(255) DEFAULT NULL COMMENT '执行器任务handler',`executor_param` varchar(512) DEFAULT NULL COMMENT '执行器任务参数',`executor_block_strategy` varchar(50) DEFAULT NULL COMMENT '阻塞处理策略',`executor_timeout` int(11) NOT NULL DEFAULT '0' COMMENT '任务执行超时时间,单位秒',`executor_fail_retry_count` int(11) NOT NULL DEFAULT '0' COMMENT '失败重试次数',`glue_type` varchar(50) NOT NULL COMMENT 'GLUE类型',`glue_source` mediumtext COMMENT 'GLUE源代码',`glue_remark` varchar(128) DEFAULT NULL COMMENT 'GLUE备注',`glue_updatetime` datetime DEFAULT NULL COMMENT 'GLUE更新时间',`child_jobid` varchar(255) DEFAULT NULL COMMENT '子任务ID,多个逗号分隔',`trigger_status` tinyint(4) NOT NULL DEFAULT '0' COMMENT '调度状态:0-停止,1-运行',`trigger_last_time` bigint(13) NOT NULL DEFAULT '0' COMMENT '上次调度时间',`trigger_next_time` bigint(13) NOT NULL DEFAULT '0' COMMENT '下次调度时间',PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;CREATE TABLE `xxl_job_log` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`job_group` int(11) NOT NULL COMMENT '执行器主键ID',`job_id` int(11) NOT NULL COMMENT '任务,主键ID',`executor_address` varchar(255) DEFAULT NULL COMMENT '执行器地址,本次执行的地址',`executor_handler` varchar(255) DEFAULT NULL COMMENT '执行器任务handler',`executor_param` varchar(512) DEFAULT NULL COMMENT '执行器任务参数',`executor_sharding_param` varchar(20) DEFAULT NULL COMMENT '执行器任务分片参数,格式如 1/2',`executor_fail_retry_count` int(11) NOT NULL DEFAULT '0' COMMENT '失败重试次数',`trigger_time` datetime DEFAULT NULL COMMENT '调度-时间',`trigger_code` int(11) NOT NULL COMMENT '调度-结果',`trigger_msg` text COMMENT '调度-日志',`handle_time` datetime DEFAULT NULL COMMENT '执行-时间',`handle_code` int(11) NOT NULL COMMENT '执行-状态',`handle_msg` text COMMENT '执行-日志',`alarm_status` tinyint(4) NOT NULL DEFAULT '0' COMMENT '告警状态:0-默认、1-无需告警、2-告警成功、3-告警失败',PRIMARY KEY (`id`),KEY `I_trigger_time` (`trigger_time`),KEY `I_handle_code` (`handle_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;CREATE TABLE `xxl_job_log_report` (`id` int(11) NOT NULL AUTO_INCREMENT,`trigger_day` datetime DEFAULT NULL COMMENT '调度-时间',`running_count` int(11) NOT NULL DEFAULT '0' COMMENT '运行中-日志数量',`suc_count` int(11) NOT NULL DEFAULT '0' COMMENT '执行成功-日志数量',`fail_count` int(11) NOT NULL DEFAULT '0' COMMENT '执行失败-日志数量',`update_time` datetime DEFAULT NULL,PRIMARY KEY (`id`),UNIQUE KEY `i_trigger_day` (`trigger_day`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;CREATE TABLE `xxl_job_logglue` (`id` int(11) NOT NULL AUTO_INCREMENT,`job_id` int(11) NOT NULL COMMENT '任务,主键ID',`glue_type` varchar(50) DEFAULT NULL COMMENT 'GLUE类型',`glue_source` mediumtext COMMENT 'GLUE源代码',`glue_remark` varchar(128) NOT NULL COMMENT 'GLUE备注',`add_time` datetime DEFAULT NULL,`update_time` datetime DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;CREATE TABLE `xxl_job_registry` (`id` int(11) NOT NULL AUTO_INCREMENT,`registry_group` varchar(50) NOT NULL,`registry_key` varchar(255) NOT NULL,`registry_value` varchar(255) NOT NULL,`update_time` datetime DEFAULT NULL,PRIMARY KEY (`id`),KEY `i_g_k_v` (`registry_group`,`registry_key`,`registry_value`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;CREATE TABLE `xxl_job_group` (`id` int(11) NOT NULL AUTO_INCREMENT,`app_name` varchar(64) NOT NULL COMMENT '执行器AppName',`title` varchar(12) NOT NULL COMMENT '执行器名称',`address_type` tinyint(4) NOT NULL DEFAULT '0' COMMENT '执行器地址类型:0=自动注册、1=手动录入',`address_list` text COMMENT '执行器地址列表,多地址逗号分隔',`update_time` datetime DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;CREATE TABLE `xxl_job_user` (`id` int(11) NOT NULL AUTO_INCREMENT,`username` varchar(50) NOT NULL COMMENT '账号',`password` varchar(50) NOT NULL COMMENT '密码',`role` tinyint(4) NOT NULL COMMENT '角色:0-普通用户、1-管理员',`permission` varchar(255) DEFAULT NULL COMMENT '权限:执行器ID列表,多个逗号分割',PRIMARY KEY (`id`),UNIQUE KEY `i_username` (`username`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;CREATE TABLE `xxl_job_lock` (`lock_name` varchar(50) NOT NULL COMMENT '锁名称',PRIMARY KEY (`lock_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;INSERT INTO `xxl_job_group`(`id`, `app_name`, `title`, `address_type`, `address_list`, `update_time`) VALUES (1, 'xxl-job-executor-sample', '示例执行器', 0, NULL, '2018-11-03 22:21:31' );
INSERT INTO `xxl_job_info`(`id`, `job_group`, `job_desc`, `add_time`, `update_time`, `author`, `alarm_email`, `schedule_type`, `schedule_conf`, `misfire_strategy`, `executor_route_strategy`, `executor_handler`, `executor_param`, `executor_block_strategy`, `executor_timeout`, `executor_fail_retry_count`, `glue_type`, `glue_source`, `glue_remark`, `glue_updatetime`, `child_jobid`) VALUES (1, 1, '测试任务1', '2018-11-03 22:21:31', '2018-11-03 22:21:31', 'XXL', '', 'CRON', '0 0 0 * * ? *', 'DO_NOTHING', 'FIRST', 'demoJobHandler', '', 'SERIAL_EXECUTION', 0, 0, 'BEAN', '', 'GLUE代码初始化', '2018-11-03 22:21:31', '');
INSERT INTO `xxl_job_user`(`id`, `username`, `password`, `role`, `permission`) VALUES (1, 'admin', 'e10adc3949ba59abbe56e057f20f883e', 1, NULL);
INSERT INTO `xxl_job_lock` ( `lock_name`) VALUES ( 'schedule_lock');commit;

在我们的数据库运行一下这些sql文件,运行完成后,会产生如下的库与对应的表

在这里插入图片描述

2、修改配置文件

此处需要修改xxl-job-admin模块下的application.properties文件,

第一:端口号(看个人)

我这边是没有改动

server.port=8080

第二:修改数据库相关配置

主要是账号和密码

### xxl-job, datasource
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/xxl_job?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai
#账号
spring.datasource.username=root
#密码
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

第三:accessToken的设置:

我这边是设置为空

### xxl-job, access token
#xxl.job.accessToken=default_token
xxl.job.accessToken=

3、启动项目

此时我们准备工作已经做完,直接启动xxl-job-admin模块下的XxlJobAdminApplication项目即可。

提示以下内容表示成功
在这里插入图片描述

4、进行访问

在浏览器输入:http://127.0.0.1:8080/xxl-job-admin 即可成功访问。
用户密码分别为:admin/123456
登陆成功后可以看到此页面即为搭建成功。
在这里插入图片描述

5、打包部署(上正式)

暂未操作

二、SpringBoot集成Xxl-Job

1. 引入xxl-job的依赖

<dependency><groupId>com.xuxueli</groupId><artifactId>xxl-job-core</artifactId><version>2.3.1</version>
</dependency>

2. 在application.yml加上xxljob的配置

#xxljob配置
xxl:job:admin:# 调度中心部署的地址 [选填]:如调度中心集群部署存在多个地址则用逗号分隔。# 执行器将会使用该地址进行"执行器心跳注册"和"任务结果回调";为空则关闭自动注册;addresses: http://localhost:8080/xxl-job-admin# 执行器通讯TOKEN [选填]:非空时启用;# 要和调度中心服务部署配置的accessToken一致,要不然无法连接注册accessToken:executor:# 执行器AppName [选填]:执行器心跳注册分组依据;为空则关闭自动注册appname: job-demo# 执行器注册 [选填]:优先使用该配置作为注册地址,为空时使用内嵌服务 ”IP:PORT“ 作为注册地址。#从而更灵活的支持容器类型执行器动态IP和动态映射端口问题。address:# 执行器IP [选填]:默认为空表示自动获取IP,多网卡时可手动设置指定IP,该IP不会绑定Host仅作为通讯实用;# 地址信息用于 "执行器注册" 和 "调度中心请求并触发任务";ip:# 执行器端口号 [选填]:小于等于0则自动获取;默认端口为9999,单机部署多个执行器时,注意要配置不同执行器端口;port: 8889# 执行器运行日志文件存储磁盘路径 [选填] :需要对该路径拥有读写权限;为空则使用默认路径;logpath: # 执行器日志文件保存天数 [选填] : 过期日志自动清理, 限制值大于等于3时生效; 否则, 如-1, 关闭自动清理功能;logretentiondays: 30

细节:

  • address的值 举例格式为 http://127.0.0.1:9999
  • 如果 address 不填, 控制器的地址取值就是 另外两个参数的组合 IP:PORT
    (ip不填就自动获取IP,port小于等于0则自动获取;默认端口为9999)
  • 如果 address 填了, 控制器的地址就是这个address

实际的启动端口 请观察控制台(port配置很重要,address配置中的端口是无法影响port的,请注意!!!)
在这里插入图片描述

配置参数讲解

属性名含义概要是否必填
addresses调度中心部署的地址如调度中心集群部署存在多个地址则用逗号(,)分隔。
执行器将会使用该地址进行"执行器心跳注册"和"任务结果回调";为空则关闭自动注册;
选填
属性名含义概要是否必填
accessToken执行器通讯TOKEN要和调度中心服务部署配置的accessToken一致,要不然无法连接注册选填
appname执行器名称执行器心跳注册分组依据;为空则关闭自动注册选填
address执行器注册地址有值时优先使用该配置作为注册地址,为空时使用内嵌服务 ”IP:PORT“ 作为注册地址。选填
ip执行器IP默认为空表示自动获取IP,多网卡时可手动设置指定IP,该IP不会绑定Host仅作为通讯实用。
地址信息用于 “执行器注册” 和 “调度中心请求并触发任务”;
选填
port执行器端口号小于等于0则自动获取;默认端口为9999,单机部署多个执行器时,注意要配置不同执行器端口必填
logpath执行器运行日志文件存储磁盘路径需要对该路径拥有读写权限;为空则使用默认路径选填
logretentiondays执行器日志文件保存天数过期日志自动清理, 限制值大于等于3时生效; 否则, 如-1, 关闭自动清理功能选填

3. 添加配置类

XxlJobConfig.java

package com.example.xxjob.config;import com.example.xxjob.job.DemoHandler;
import com.xxl.job.core.executor.XxlJobExecutor;
import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.util.Arrays;@Configuration
@Slf4j
public class XxlJobConfig {@Value("${xxl.job.admin.addresses}")private String adminAddresses;@Value("${xxl.job.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;@Beanpublic XxlJobSpringExecutor xxlJobExecutor() {log.info(">>>>>>>>>>> start xxl-job config init. >>>>>>>>");XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();//调度中心服务部署的地址xxlJobSpringExecutor.setAdminAddresses(adminAddresses);//执行器AppNamexxlJobSpringExecutor.setAppname(appname);//一般情况下Address何二ip用不上)xxlJobSpringExecutor.setAddress(address);xxlJobSpringExecutor.setIp(ip);//执行器端口号xxlJobSpringExecutor.setPort(port);//一般情况下AccessToken用不上xxlJobSpringExecutor.setAccessToken(accessToken);//执行器运行日志文件存储磁盘路径xxlJobSpringExecutor.setLogPath(logPath);//执行器日志文件保存天数xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays);log.info(">>>>>>>>>>> end xxl-job config init. >>>>>>>>");return xxlJobSpringExecutor;}
}

4. 添加xxl-job测试(由调度中心进行测试)

1.先在自己的Springboot项目中创建测试类

@Slf4j
@Component
public class XxlJobTest {//配置运行模式名称@XxlJob("xxlJobTest")public ReturnT<String> xxlJobTest(String date) {log.info("---------xxlJobTest定时任务执行成功--------");return ReturnT.SUCCESS;}}

2. 再进入已经启动成功的调度中心页面中进行操作

1.根据 配置文件 新增 执行器
在这里插入图片描述
关于注册方式:自动注册和手动注册

  • 自动注册:AppName 不能乱填,要和配置文件统一,它才能自动注册进去
  • 手动注册:AppName 可以随意填写,但是机器地址就要需要填写正确
    (比如本地就是http://127.0.0.1:8889,其中这个8889来自于配置文件里面port参数)

2.根据 @XxlJob标注的方法 配置 执行器任务

我这边上面测试方法用的是 @XxlJob(“xxlJobTest”) 标注的

配置的任务时,要选好之前的执行器,再配置cros表达式和相应的方法
在这里插入图片描述

点击启动

在这里插入图片描述

就可以看到后台的这个方法被触发(5秒一次)

在这里插入图片描述

5. 动态API调度任务 (看个人需求)

通过API方式(或者方法函数),我们动态随意地去 增删改查、设置定时规则等等去调度任务。

在 xxl-job-admin 项目中

1. 新建 MyDynamicApiController

在这里插入图片描述

package com.xxl.job.admin.controller;import com.xxl.job.admin.controller.annotation.PermissionLimit;
import com.xxl.job.admin.core.cron.CronExpression;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobQuery;
import com.xxl.job.admin.core.thread.JobScheduleHelper;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.admin.service.LoginService;
import com.xxl.job.admin.service.XxlJobService;
import com.xxl.job.core.biz.model.ReturnT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.Date;
import java.util.Map;/*** @Author: JCccc* @Date: 2022-6-2 14:23* @Description: xxl job rest api*/
@RestController
@RequestMapping("/api/jobinfo")
public class MyDynamicApiController {private static Logger logger = LoggerFactory.getLogger(MyDynamicApiController.class);@Autowiredprivate XxlJobService xxlJobService;@Autowiredprivate LoginService loginService;@RequestMapping(value = "/pageList",method = RequestMethod.POST)public Map<String, Object> pageList(@RequestBody XxlJobQuery xxlJobQuery) {return xxlJobService.pageList(xxlJobQuery.getStart(),xxlJobQuery.getLength(),xxlJobQuery.getJobGroup(),xxlJobQuery.getTriggerStatus(),xxlJobQuery.getJobDesc(),xxlJobQuery.getExecutorHandler(),xxlJobQuery.getAuthor());}@PostMapping("/save")public ReturnT<String> add(@RequestBody(required = true)XxlJobInfo jobInfo) {// next trigger time (5s后生效,避开预读周期)long nextTriggerTime = 0;try {Date nextValidTime = new CronExpression(jobInfo.getScheduleConf()).getNextValidTimeAfter(new Date(System.currentTimeMillis() + JobScheduleHelper.PRE_READ_MS));if (nextValidTime == null) {return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("jobinfo_field_cron_never_fire"));}nextTriggerTime = nextValidTime.getTime();} catch (ParseException e) {logger.error(e.getMessage(), e);return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("jobinfo_field_cron_unvalid")+" | "+ e.getMessage());}jobInfo.setTriggerStatus(1);jobInfo.setTriggerLastTime(0);jobInfo.setTriggerNextTime(nextTriggerTime);jobInfo.setUpdateTime(new Date());if(jobInfo.getId()==0){return xxlJobService.add(jobInfo);}else{return xxlJobService.update(jobInfo);}}@RequestMapping(value = "/delete",method = RequestMethod.GET)public ReturnT<String> delete(int id) {return xxlJobService.remove(id);}@RequestMapping(value = "/start",method = RequestMethod.GET)public ReturnT<String> start(int id) {return xxlJobService.start(id);}@RequestMapping(value = "/stop",method = RequestMethod.GET)public ReturnT<String> stop(int id) {return xxlJobService.stop(id);}@RequestMapping(value="login", method=RequestMethod.GET)@PermissionLimit(limit=false)public ReturnT<String> loginDo(HttpServletRequest request, HttpServletResponse response, String userName, String password, String ifRemember){boolean ifRem = (ifRemember!=null && ifRemember.trim().length()>0 && "on".equals(ifRemember))?true:false;ReturnT<String> result= loginService.login(request, response, userName, password, ifRem);return result;}
}
2. 创建 XxlJobQuery

在这里插入图片描述

package com.xxl.job.admin.core.model;/*** @Author: JCccc* @Date: 2022-6-2 14:23* @Description: xxl job rest api*/
public class XxlJobQuery {private int start;private int length;private int triggerStatus;private String jobDesc;private String executorHandler;private String author;private int jobGroup;public int getStart() {return start;}public void setStart(int start) {this.start = start;}public int getLength() {return length;}public void setLength(int length) {this.length = length;}public int getTriggerStatus() {return triggerStatus;}public void setTriggerStatus(int triggerStatus) {this.triggerStatus = triggerStatus;}public String getJobDesc() {return jobDesc;}public void setJobDesc(String jobDesc) {this.jobDesc = jobDesc;}public String getExecutorHandler() {return executorHandler;}public void setExecutorHandler(String executorHandler) {this.executorHandler = executorHandler;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}public int getJobGroup() {return jobGroup;}public void setJobGroup(int jobGroup) {this.jobGroup = jobGroup;}
}

在 自己的 SpringBoot 项目中

加maven依赖
      <!--(一个是fastjson,大家别学我,我是为了实战示例图方便,用的JsonObject来传参)--><!--(一个是httpClient ,用于调用admin服务的api接口)--><dependency><groupId>commons-httpclient</groupId><artifactId>commons-httpclient</artifactId><version>3.1</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.47</version></dependency>
1.创建 XxlJobInfo 类

这个就是原作者的使用的实体类

import java.util.Date;/*** xxl-job info** @author xuxueli  2016-1-12 18:25:49*/
public class XxlJobInfo {private int id;       // 主键IDprivate int jobGroup;   // 执行器主键IDprivate String jobDesc;     // 备注private String jobCron;private Date addTime;private Date updateTime;private String author;    // 负责人private String alarmEmail;  // 报警邮件private String scheduleType;      // 调度类型private String scheduleConf;      // 调度配置,值含义取决于调度类型private String misfireStrategy;     // 调度过期策略private String executorRouteStrategy; // 执行器路由策略private String executorHandler;       // 执行器,任务Handler名称private String executorParam;       // 执行器,任务参数private String executorBlockStrategy; // 阻塞处理策略private int executorTimeout;        // 任务执行超时时间,单位秒private int executorFailRetryCount;   // 失败重试次数private String glueType;    // GLUE类型 #com.xxl.job.core.glue.GlueTypeEnumprivate String glueSource;    // GLUE源代码private String glueRemark;    // GLUE备注private Date glueUpdatetime;  // GLUE更新时间private String childJobId;    // 子任务ID,多个逗号分隔private int triggerStatus;    // 调度状态:0-停止,1-运行private long triggerLastTime; // 上次调度时间private long triggerNextTime; // 下次调度时间public String getJobCron() {return jobCron;}public void setJobCron(String jobCron) {this.jobCron = jobCron;}public int getId() {return id;}public void setId(int id) {this.id = id;}public int getJobGroup() {return jobGroup;}public void setJobGroup(int jobGroup) {this.jobGroup = jobGroup;}public String getJobDesc() {return jobDesc;}public void setJobDesc(String jobDesc) {this.jobDesc = jobDesc;}public Date getAddTime() {return addTime;}public void setAddTime(Date addTime) {this.addTime = addTime;}public Date getUpdateTime() {return updateTime;}public void setUpdateTime(Date updateTime) {this.updateTime = updateTime;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}public String getAlarmEmail() {return alarmEmail;}public void setAlarmEmail(String alarmEmail) {this.alarmEmail = alarmEmail;}public String getScheduleType() {return scheduleType;}public void setScheduleType(String scheduleType) {this.scheduleType = scheduleType;}public String getScheduleConf() {return scheduleConf;}public void setScheduleConf(String scheduleConf) {this.scheduleConf = scheduleConf;}public String getMisfireStrategy() {return misfireStrategy;}public void setMisfireStrategy(String misfireStrategy) {this.misfireStrategy = misfireStrategy;}public String getExecutorRouteStrategy() {return executorRouteStrategy;}public void setExecutorRouteStrategy(String executorRouteStrategy) {this.executorRouteStrategy = executorRouteStrategy;}public String getExecutorHandler() {return executorHandler;}public void setExecutorHandler(String executorHandler) {this.executorHandler = executorHandler;}public String getExecutorParam() {return executorParam;}public void setExecutorParam(String executorParam) {this.executorParam = executorParam;}public String getExecutorBlockStrategy() {return executorBlockStrategy;}public void setExecutorBlockStrategy(String executorBlockStrategy) {this.executorBlockStrategy = executorBlockStrategy;}public int getExecutorTimeout() {return executorTimeout;}public void setExecutorTimeout(int executorTimeout) {this.executorTimeout = executorTimeout;}public int getExecutorFailRetryCount() {return executorFailRetryCount;}public void setExecutorFailRetryCount(int executorFailRetryCount) {this.executorFailRetryCount = executorFailRetryCount;}public String getGlueType() {return glueType;}public void setGlueType(String glueType) {this.glueType = glueType;}public String getGlueSource() {return glueSource;}public void setGlueSource(String glueSource) {this.glueSource = glueSource;}public String getGlueRemark() {return glueRemark;}public void setGlueRemark(String glueRemark) {this.glueRemark = glueRemark;}public Date getGlueUpdatetime() {return glueUpdatetime;}public void setGlueUpdatetime(Date glueUpdatetime) {this.glueUpdatetime = glueUpdatetime;}public String getChildJobId() {return childJobId;}public void setChildJobId(String childJobId) {this.childJobId = childJobId;}public int getTriggerStatus() {return triggerStatus;}public void setTriggerStatus(int triggerStatus) {this.triggerStatus = triggerStatus;}public long getTriggerLastTime() {return triggerLastTime;}public void setTriggerLastTime(long triggerLastTime) {this.triggerLastTime = triggerLastTime;}public long getTriggerNextTime() {return triggerNextTime;}public void setTriggerNextTime(long triggerNextTime) {this.triggerNextTime = triggerNextTime;}
}
2.创建 XxlJobUtil 类
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;/*** @Author: JCccc* @Date: 2022-6-22 9:51* @Description:*/
public class XxlJobUtil {private static String cookie="";/*** 查询现有的任务(可以关注这个整个调用链,可以自己模仿着写其他的拓展接口)* @param url* @param requestInfo* @return* @throws HttpException* @throws IOException*/public static JSONObject pageList(String url,JSONObject requestInfo) throws HttpException, IOException {String path = "/api/jobinfo/pageList";String targetUrl = url + path;HttpClient httpClient = new HttpClient();PostMethod post = new PostMethod(targetUrl);post.setRequestHeader("cookie", cookie);RequestEntity requestEntity = new StringRequestEntity(requestInfo.toString(), "application/json", "utf-8");post.setRequestEntity(requestEntity);httpClient.executeMethod(post);JSONObject result = new JSONObject();result = getJsonObject(post, result);System.out.println(result.toJSONString());return result;}/*** 新增/编辑任务* @param url* @param requestInfo* @return* @throws HttpException* @throws IOException*/public static JSONObject addJob(String url,JSONObject requestInfo) throws HttpException, IOException {String path = "/api/jobinfo/save";String targetUrl = url + path;HttpClient httpClient = new HttpClient();PostMethod post = new PostMethod(targetUrl);post.setRequestHeader("cookie", cookie);RequestEntity requestEntity = new StringRequestEntity(requestInfo.toString(), "application/json", "utf-8");post.setRequestEntity(requestEntity);httpClient.executeMethod(post);JSONObject result = new JSONObject();result = getJsonObject(post, result);System.out.println(result.toJSONString());return result;}/*** 删除任务* @param url* @param id* @return* @throws HttpException* @throws IOException*/public static JSONObject deleteJob(String url,int id) throws HttpException, IOException {String path = "/api/jobinfo/delete?id="+id;return doGet(url,path);}/*** 开始任务* @param url* @param id* @return* @throws HttpException* @throws IOException*/public static JSONObject startJob(String url,int id) throws HttpException, IOException {String path = "/api/jobinfo/start?id="+id;return doGet(url,path);}/*** 停止任务* @param url* @param id* @return* @throws HttpException* @throws IOException*/public static JSONObject stopJob(String url,int id) throws HttpException, IOException {String path = "/api/jobinfo/stop?id="+id;return doGet(url,path);}public static JSONObject doGet(String url,String path) throws HttpException, IOException {String targetUrl = url + path;HttpClient httpClient = new HttpClient();HttpMethod get = new GetMethod(targetUrl);get.setRequestHeader("cookie", cookie);httpClient.executeMethod(get);JSONObject result = new JSONObject();result = getJsonObject(get, result);return result;}private static JSONObject getJsonObject(HttpMethod postMethod, JSONObject result) throws IOException {if (postMethod.getStatusCode() == HttpStatus.SC_OK) {InputStream inputStream = postMethod.getResponseBodyAsStream();BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));StringBuffer stringBuffer = new StringBuffer();String str;while((str = br.readLine()) != null){stringBuffer.append(str);}String response = new String(stringBuffer);br.close();return (JSONObject) JSONObject.parse(response);} else {return null;}}/*** 登录* @param url* @param userName* @param password* @return* @throws HttpException* @throws IOException*/public static String login(String url, String userName, String password) throws HttpException, IOException {String path = "/api/jobinfo/login?userName="+userName+"&password="+password;String targetUrl = url + path;HttpClient httpClient = new HttpClient();HttpMethod get = new GetMethod((targetUrl));httpClient.executeMethod(get);if (get.getStatusCode() == 200) {Cookie[] cookies = httpClient.getState().getCookies();StringBuffer tmpcookies = new StringBuffer();for (Cookie c : cookies) {tmpcookies.append(c.toString() + ";");}cookie = tmpcookies.toString();} else {try {cookie = "";} catch (Exception e) {cookie="";}}return cookie;}
}
3. 创建 XxlJobController 进行测试

(用于模拟触发我们的任务创建、编辑、删除、停止等等)

import java.util.Date;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;/*** @Author: JCccc* @Date: 2022-6-22 9:26* @Description:*/
@RestController
public class XxlJobController {@RequestMapping(value = "/pageList",method = RequestMethod.GET)public Object pageList() throws IOException {//int jobGroup, int triggerStatus, String jobDesc, String executorHandler, String authorJSONObject test=new JSONObject();test.put("length",10);XxlJobUtil.login("http://127.0.0.1:8961/xxl-job-admin","admin","123456");JSONObject response = XxlJobUtil.pageList("http://127.0.0.1:8961/xxl-job-admin", test);return  response.get("data");}@RequestMapping(value = "/add",method = RequestMethod.GET)public void add() throws IOException {XxlJobInfo xxlJobInfo=new XxlJobInfo();xxlJobInfo.setJobCron("0/5 * * * * ?");xxlJobInfo.setJobGroup(3);xxlJobInfo.setJobDesc("我来试试");xxlJobInfo.setAddTime(new Date());xxlJobInfo.setUpdateTime(new Date());xxlJobInfo.setAuthor("JCccc");xxlJobInfo.setAlarmEmail("864477182@com");xxlJobInfo.setScheduleType("CRON");xxlJobInfo.setScheduleConf("0/5 * * * * ?");xxlJobInfo.setMisfireStrategy("DO_NOTHING");xxlJobInfo.setExecutorRouteStrategy("FIRST");xxlJobInfo.setExecutorHandler("clockInJobHandler");xxlJobInfo.setExecutorParam("att");xxlJobInfo.setExecutorBlockStrategy("SERIAL_EXECUTION");xxlJobInfo.setExecutorTimeout(0);xxlJobInfo.setExecutorFailRetryCount(1);xxlJobInfo.setGlueType("BEAN");xxlJobInfo.setGlueSource("");xxlJobInfo.setGlueRemark("GLUE代码初始化");xxlJobInfo.setGlueUpdatetime(new Date());JSONObject test = (JSONObject) JSONObject.toJSON(xxlJobInfo);XxlJobUtil.login("http://127.0.0.1:8961/xxl-job-admin","admin","123456");JSONObject response = XxlJobUtil.addJob("http://127.0.0.1:8961/xxl-job-admin", test);if (response.containsKey("code") && 200 == (Integer) response.get("code")) {System.out.println("新增成功");} else {System.out.println("新增失败");}}@RequestMapping(value = "/stop/{jobId}",method = RequestMethod.GET)public void stop(@PathVariable("jobId") Integer jobId) throws IOException {XxlJobUtil.login("http://127.0.0.1:8961/xxl-job-admin","admin","123456");JSONObject response = XxlJobUtil.stopJob("http://127.0.0.1:8961/xxl-job-admin", jobId);if (response.containsKey("code") && 200 == (Integer) response.get("code")) {System.out.println("任务停止成功");} else {System.out.println("任务停止失败");}}@RequestMapping(value = "/delete/{jobId}",method = RequestMethod.GET)public void delete(@PathVariable("jobId") Integer jobId) throws IOException {XxlJobUtil.login("http://127.0.0.1:8961/xxl-job-admin","admin","123456");JSONObject response = XxlJobUtil.deleteJob("http://127.0.0.1:8961/xxl-job-admin", jobId);if (response.containsKey("code") && 200 == (Integer) response.get("code")) {System.out.println("任务移除成功");} else {System.out.println("任务移除失败");}}@RequestMapping(value = "/start/{jobId}",method = RequestMethod.GET)public void start(@PathVariable("jobId") Integer jobId) throws IOException {XxlJobUtil.login("http://127.0.0.1:8961/xxl-job-admin","admin","123456");JSONObject response = XxlJobUtil.startJob("http://127.0.0.1:8961/xxl-job-admin", jobId);if (response.containsKey("code") && 200 == (Integer) response.get("code")) {System.out.println("任务启动成功");} else {System.out.println("任务启动失败");}}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/404709.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

stm32的UART重定向printf()

1配置好uart 2打开usart.c文件 3在此文件前面添加头文件 4在末尾添加重定向代码 添加的代码 /* USER CODE BEGIN 1 *///加入以下代码,支持printf函数,而不需要选择use MicroLIB //#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f) #if 1 //#pragma import(__use_n…

day01- Web开发介绍-HTML-CS

Web开发介绍 1 什么是web开发 Web&#xff1a;全球广域网&#xff0c;也称为万维网(www World Wide Web)&#xff0c;能够通过浏览器访问的网站。 所以Web开发说白了&#xff0c;就是开发网站的&#xff0c;例如下图所示的网站&#xff1a;淘宝&#xff0c;京东等等 那么我们…

JavaEE过滤器的创建与使用过滤器的使用场景

过滤器 Filter也称之为过滤器&#xff0c;过滤器是javaEE规范肿定义的一种技术,可以让请求到达目标servlet之前,先进入到过滤器中,在过滤器中统一进行一些拦截处理,当处理完成后,可以继续向后执行,到达目标servlet,如果配置了多个过滤器,也可以进入下一个过滤器 创建过滤器 创…

asyncua模块实现OPC UA通讯

asyncua是OPCUA的python实现&#xff0c;使用起来非常方便&#xff0c;其github地址是https://github.com/FreeOpcUa/opcua-asyncio UaExpert是OPC UA Client的GUI工具&#xff0c;当编写好server代码后并运行&#xff0c;我们可以使用UaExpert去和server进行通信。UaExpert使…

小程序使用微信支付

接入小程序需要后端进行注册&#xff0c;前端只需要调用API即可。 大概流程如下&#xff1a; 本例使用一个购买商品的例子&#xff0c;前端点击微信支付&#xff0c;后端生成一个商品订单&#xff0c;然后向微信支付系统发起请求&#xff0c;生成一个微信的预支付订单&#xff…

windows上传的文本在linux执行不了,格式转换

在windows编辑的文件脚本上传到linux里面执行不了 1.现象描述 比如在windows编辑简单的文本 2.上传到linux后执行无结果 无响应 3.编码问题 比普通文件多了with CRLF line terminators结尾格式。 cat -v 可以让隐藏的转义字符也打印中显示 4.原因windows和linux的换行符不…

数字化办公OA系统是如何运作的——办公物品领用功能拆解

数字化办公 OA 系统究竟是如何运作的呢&#xff1f;它的核心功能又是如何发挥作用的呢&#xff1f;这篇就以行政 OA 系统为例&#xff0c;从产品视角来深入探讨它是如何运作的。 简道云行政OA管理系统模板&#xff0c;可以直接查看和使用&#xff1a;https://www.jiandaoyun.co…

springboot纹理生成图片系统--论文源码调试讲解

第2章 程序开发技术 2.1 MySQL数据库 开发的程序面向用户的只是程序的功能界面&#xff0c;让用户操作程序界面的各个功能&#xff0c;那么很多人就会问&#xff0c;用户使用程序功能生成的数据信息放在哪里的&#xff1f;这个就需要涉及到数据库的知识了&#xff0c;一般来说…

地平线旭日X3开发板--使用Opencv显示CSI摄像头例程

调试过程发现旭日派无法直接用opencv的VideoCapture()调用CSI摄像头, 需要使用libsrcampy库来获取CSI摄像头图像, 但是从libsrcampy获取的摄像头图像格式是NV12,无法直接在opencv上显示或者处理, 为了能够使用opencv的API来处理图像, 需要增加NV12转化成bgr像素格式的…

springboot项目配置https安装ssl证书教程

1.将下载的ssl证书文件中的jks后缀文件放在/src/main/resource文件夹里面 2.在配置文件中&#xff08;yml后缀配置文件的格式不同&#xff09;添加如下配置即可

ensp小实验(ospf+dhcp+防火墙)

前言 今天给大家分享一个ensp的小实验&#xff0c;里面包含了ospf、dhcp、防火墙的内容&#xff0c;如果需要文件的可以私我。 一、拓扑图 二、实训需求 某学校新建一个分校区网络&#xff0c;经过与校领导和网络管理员的沟通&#xff0c;现通过了设备选型和组网解决方案&…

运维学习————nginx-入门及反向代理搭建

目录 一、简介 二、正向代理和反向代理 1、正向代理 作用 2、反向代理 作用 三、单机版nginx部署 1、查看环境 2、环境安装以及nginx安装 2.1、安装pcre 2.2、安装gzip模块需要 zlib 库 2.3、安装Nginx 3、启动测试 四、反向代理配置 一、简介 nginx [engine x] 是…

计算机Java项目|基于SpringBoot的大学生一体化服务平台的设计与实现

作者主页&#xff1a;编程指南针 作者简介&#xff1a;Java领域优质创作者、CSDN博客专家 、CSDN内容合伙人、掘金特邀作者、阿里云博客专家、51CTO特邀作者、多年架构师设计经验、多年校企合作经验&#xff0c;被多个学校常年聘为校外企业导师&#xff0c;指导学生毕业设计并参…

C++入门——16C++11新特性

1.列表初始化 初始化列表时&#xff0c;可添加等号()&#xff0c;也可不添加。 struct Point {int _x;int _y; };int main() {int x1 1;int x2{ 2 };int array1[]{ 1, 2, 3, 4, 5 };int array2[5]{ 0 };Point p{ 1, 2 };// C11中列表初始化也可以适用于new表达式中int* pa …

POK´ELLMON:在宝可梦战斗中实现人类水平的人工智能

人工智能咨询培训老师叶梓 转载标明出处 最近&#xff0c;由美国乔治亚理工学院的Sihao Hu、Tiansheng Huang和Ling Liu发表的论文介绍了POKELLMON&#xff0c;这是一个开创性的基于大模型&#xff08;LLM&#xff09;的具身智能体&#xff0c;它在战术战斗游戏中&#xff0c;特…

海康VisionMaster使用学习笔记11-VisionMaster基本操作

VisionMaster基本操作 VM示例方案 1. 工具拖拽及使用方式 分别从采集和定位栏里拖拽图像源,快速匹配,Blob分析工具 2. 模块连线 依次连线 3.如何订阅 点击快速匹配,可以看到输入源已订阅了图像1的图像,Blob分析类似 4. 方案操作及全局触发 点击快速匹配,创建特征模版,框选…

【Hot100】LeetCode—2. 两数相加

目录 1- 思路思路 2- 实现⭐2. 两数相加——题解思路 3- ACM 实现 原题连接&#xff1a;2. 两数相加 1- 思路 思路 分为几个步骤 ①数据结构&#xff1a;遍历指针,进位符、②遍历两个链表、③处理最后的进位符 1- 数据结构 定义 curA 和 curB 用来遍历两个链表定义 carry 记…

慎投!4本SCI/SSCI期刊被剔,8月WOS已更新!

SCI/SSCI期刊目录8月份已更新&#xff01;快来查收最新动态&#xff01;如有相关领域作者有意投稿&#xff0c;可作为重点关注&#xff01; ​ 期刊动态 ​ 2024年8月科睿唯安期刊目录更新 2024年8月20日&#xff0c;科睿唯安更新了WOS期刊目录&#xff0c;此次更新&#x…

O2OA(翱途)服务器配置与管理-如何修改服务器内存占用率?

o2server 启动后一般占用大约4G~6G内存空间,在启动脚本中默认设置 -Xms2g 限定heap(堆)的大小最小2G,可以通过设置-Xmx来设置堆的上限. Xms -Xms2g:设置JVM初始堆内存为2g.此值可以设置与-Xmx相同,以避免每次垃圾回收完成后JVM重新分配内存. Xmx -Xmx5g:设置JVM最大堆内存为5g.…

ES-分布式搜索引擎

DSL查询文档 精确查询 、 我附近的人 实例 根据页码跳转无法使用 高亮