Springboot整合 xxljob,自定义添加、修改、删除、停止、启动任务

目录

一、模拟登录方式

二、注解方式

三、访问者调用

四、测试


本次自定义方式分为两种:一种是模拟登录,另一种是使用注解的方式

一、模拟登录方式

修改xxl-job-admin工程,在controller里面添加一个MyApiController,在里面添加自定义的增删等方法

@RestController
@RequestMapping("/api/myjobinfo")
public class MyApiController {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) {long nextTriggerTime = 0;try {Date nextValidTime = new CronExpression(jobInfo.getJobCron()).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;}
}

此方式优点:除了登录接口为,其他接口都需要校验,缺点:调用接口前需要登录,比较繁琐

二、注解方式

在项目中,有一个JobInfoController类,,这个类就是处理各种新增任务,修改任务,触发任务;但这些接口都是后台管理页面使用的,要想调用就必须要先登录,也就是方式一,然而xxl-job已经为我们提供了一个注解,通过这个注解的配置可以跳过登录进行访问,这个注解就是 @PermissionLimit(limit = false) ,将limit设置为false即可,默认是true,也就是需要做登录验证。我们可以在自己定义的Controller上使用这个注解。

@RestController
@RequestMapping("/api/myjobinfo")
public class MyApiController {@RequestMapping("/add")@ResponseBody@PermissionLimit(limit = false)public ReturnT<String> addJobInfo(@RequestBody XxlJobInfo jobInfo) {return xxlJobService.add(jobInfo);}@RequestMapping("/update")@ResponseBody@PermissionLimit(limit = false)public ReturnT<String> updateJobCron(@RequestBody XxlJobInfo jobInfo) {return xxlJobService.updateCron(jobInfo);}@RequestMapping("/remove")@ResponseBody@PermissionLimit(limit = false)public ReturnT<String> removeJob(@RequestBody XxlJobInfo jobInfo) {return xxlJobService.remove(jobInfo.getId());}@RequestMapping("/pauseJob")@ResponseBody@PermissionLimit(limit = false)public ReturnT<String> pauseJob(@RequestBody XxlJobInfo jobInfo) {return xxlJobService.stop(jobInfo.getId());}@RequestMapping("/start")@ResponseBody@PermissionLimit(limit = false)public ReturnT<String> startJob(@RequestBody XxlJobInfo jobInfo) {return xxlJobService.start(jobInfo.getId());}@RequestMapping("/stop")@ResponseBodypublic ReturnT<String> pause(int id) {return xxlJobService.stop(id);}@RequestMapping("/addAndStart")@ResponseBody@PermissionLimit(limit = false)public ReturnT<String> addAndStart(@RequestBody XxlJobInfo jobInfo) {ReturnT<String> result = xxlJobService.add(jobInfo);int id = Integer.valueOf(result.getContent());xxlJobService.start(id);return result;}}

该方式的优点:无需登录可以直接调用接口,缺点:接口全部暴露有一定的风险。

将admin项目编译打包后放入服务器,客户端就可以开始调用了....

三、访问者调用

1、创建实体

@Data
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;	// 下次调度时间
}

2、创建一个工具类

也可以不创建直接调用

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;}
}

如果是方式二可以直接调用,无需登录

四、测试

如果是方式二,无需登录,也就不用再请求头里面设置cookie

@RestController
public class TestController {@Value("${xxl.job.admin.addresses:''}")private String adminAddresses;@Value("${xxl.job.admin.login-username:admin}")private String loginUsername;@Value("${xxl.job.admin.login-pwd:123456}")private String loginPwd;//登陆private void xxljob_login(){try {XxlJobUtil.login(adminAddresses,loginUsername,loginPwd);} catch (IOException e) {throw new RuntimeException(e);}}@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);xxljob_login();JSONObject response = XxlJobUtil.pageList(adminAddresses, test);return  response.get("data");}@RequestMapping(value = "/add",method = RequestMethod.GET)public Object add() throws IOException {XxlJobInfo xxlJobInfo=new XxlJobInfo();xxlJobInfo.setJobCron("0/1 * * * * ?");xxlJobInfo.setJobGroup(3);xxlJobInfo.setJobDesc("Test XXl-job");xxlJobInfo.setAddTime(new Date());xxlJobInfo.setUpdateTime(new Date());xxlJobInfo.setAuthor("Test");xxlJobInfo.setAlarmEmail("1234567@com");xxlJobInfo.setScheduleType("CRON");xxlJobInfo.setScheduleConf("0/1 * * * * ?");xxlJobInfo.setMisfireStrategy("DO_NOTHING");xxlJobInfo.setExecutorRouteStrategy("FIRST");xxlJobInfo.setExecutorHandler("clockInJobHandler_1");xxlJobInfo.setExecutorParam("att");xxlJobInfo.setExecutorBlockStrategy("SERIAL_EXECUTION");xxlJobInfo.setExecutorTimeout(0);xxlJobInfo.setExecutorFailRetryCount(1);xxlJobInfo.setGlueType("BEAN");xxlJobInfo.setGlueSource("");xxlJobInfo.setGlueRemark("初始化");xxlJobInfo.setGlueUpdatetime(new Date());JSONObject test = (JSONObject) JSONObject.toJSON(xxlJobInfo);xxljob_login();JSONObject response = XxlJobUtil.addJob(adminAddresses, test);if (response.containsKey("code") && 200 == (Integer) response.get("code")) {String jobId = response.getString("content");System.out.println("新增成功,jobId:" + jobId);} else {System.out.println("新增失败");}return response;}@RequestMapping(value = "/stop/{jobId}",method = RequestMethod.GET)public void stop(@PathVariable("jobId") Integer jobId) throws IOException {xxljob_login();JSONObject response = XxlJobUtil.stopJob(adminAddresses, 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 {xxljob_login();JSONObject response = XxlJobUtil.deleteJob(adminAddresses, 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 {xxljob_login();JSONObject response = XxlJobUtil.startJob(adminAddresses, jobId);if (response.containsKey("code") && 200 == (Integer) response.get("code")) {System.out.println("任务启动成功");} else {System.out.println("任务启动失败");}}}

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

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

相关文章

STM32F407使用ESP8266实现阿里云OTA(中)

文章目录 前言一、程序分析二、程序讲解1. main函数2. Get_Version()函数3. esp_Init()函数4. Check_Updata()函数结语前言 从上一章STM32F407使用ESP8266实现阿里云OTA(上)中我们已经对连接阿里云和从阿里云获取升级包的流程非常的熟悉了。所以本章我们进行STM32的程序开发…

Docker部署DeepSeek常见问题及解决方案

在使用Docker部署DeepSeek的过程中,许多开发者可能会遇到一些常见问题。本文整理了几个高频问题及其解决方案,帮助大家更顺利地完成部署。 镜像拉取失败 问题现象 执行 docker pull 命令时,提示超时或镜像不存在。 可能原因 1. 网络环境不稳定,导致连接Docker Hub失败…

Linux 内核 IPv4 套接字创建机制与协议表管理深度解析

一、inet_create:IPv4 套接字创建的核心引擎 1.1 核心功能与执行流程 inet_create 是 Linux 内核处理 socket(AF_INET, type, protocol) 系统调用的核心实现,主要完成以下关键任务: 协议匹配与初始化:根据套接字类型和协议号匹配协议处理模块 资源分配:创建并初始化套接…

网络:手写HTTP

目录 一、HTTP是应用层协议 二、HTTP服务器 三、HTTP服务 认识请求中的uri HTTP支持默认首页 响应 功能完善 套接字复用 一、HTTP是应用层协议 HTTP下层是TCP协议&#xff0c;站在TCP的角度看&#xff0c;要提供的服务是HTTP服务。 这是在原来实现网络版计算器时&am…

论文笔记(七十八)Do generative video models understand physical principles?

Do generative video models understand physical principles? 文章概括Physics-IQ基准数据集评估协议为什么要创建一个真实世界的Physics-IQ数据集模型物理理解的评估指标动作发生在哪里&#xff1f;空间IoU&#xff08;Spatial IoU&#xff09;动作在哪里、何时发生&#xf…

AXP2101入门

目录 核心功能与特性封装与配置安全与可靠性 AXP2101 是一款由全志公司开发的单电池 NVDC 电源管理集成电路&#xff08;PMIC&#xff09;&#xff0c;专为锂离子/锂聚合物单电池应用设计&#xff0c;适用于需要多通道电源输出的设备。 核心功能与特性 1.输入与充电管理 输入…

DAY8:Oracle高可用架构深度解析与Data Guard单节点搭建实战

引言 在数据库领域&#xff0c;高可用性&#xff08;High Availability&#xff09;是保障业务连续性的核心要求。Oracle作为企业级数据库的领导者&#xff0c;提供了RAC、Data Guard、GoldenGate三大核心方案。本文将深入剖析这些技术的实现原理&#xff0c;并手把手指导搭建…

游戏引擎学习第243天:异步纹理下载

仓库 https://gitee.com/mrxiao_com/2d_game_6 https://gitee.com/mrxiao_com/2d_game_5 回顾并为今天设定阶段 目前的开发工作主要回到了图形渲染相关的部分。我们之前写了自己的软件渲染器&#xff0c;这个渲染器性能意外地好&#xff0c;甚至可以以相对不错的帧率运行过场…

BBRv2,v3 吞吐为什么不如 BBRv1

为什么 BBRv2/3 测试下来吞吐远不如 2016 年底的 BBRv1&#xff0c;这个事曾经提到过很多次&#xff0c;今天分析一下原理。注意三个事实&#xff1a; BBR 是一种拥塞控制算法&#xff1b;BBR 已经迭代到了 v3 版本&#xff1b;BBRv3 的 “性能” 远不如 BBRv1. 第二点有点不…

前端项目搭建集锦:vite、vue、react、antd、vant、ts、sass、eslint、prettier、浏览器扩展,开箱即用,附带项目搭建教程

前端项目搭建集锦&#xff1a;vite、vue、react、antd、vant、ts、sass、eslint、prettier、浏览器扩展&#xff0c;开箱即用&#xff0c;附带项目搭建教程 前言&#xff1a;一、Vue项目下载快速通道二、React项目下载快速通道三、BrowserPlugins项目下载快速通道四、项目搭建教…

蓝桥杯 15.小数第n位

小数第n位 原题目链接 题目描述 我们知道&#xff0c;整数做除法时&#xff0c;有时会得到有限小数&#xff0c;有时会得到无限循环小数。 如果我们把有限小数的末尾加上无限多个 0&#xff0c;它们就具有了统一的形式。 本题的任务是&#xff1a;在上述约定下&#xff0c…

【Docker】在Ubuntu平台上的安装部署

写在前面 docker作为一种部署项目的辅助工具&#xff0c;真是太好用了需要魔法&#xff0c;不然无法正常运行笔者环境&#xff1a;ubuntu22.04 具体步骤 更新系统包索引 sudo apt update安装必要依赖包 sudo apt install -y apt-transport-https ca-certificates curl softwa…

Spring Boot默认缓存管理

Spring框架支持透明地向应用程序添加缓存&#xff0c;以及对缓存进行管理&#xff0c;其管理缓存的核心是将缓存应用于操作数据的方法&#xff0c;从而减少操作数据的执行次数&#xff0c;同时不会对程序本身造成任何干扰。Spring Boot继承了Spring框架的缓存管理功能&#xff…

数模学习:一,层次分析法

基本定位&#xff1a; 适用于解决评价&#xff0c;选择类问题&#xff08;数值不确定&#xff0c;需要自己结合资料数据等自己填写&#xff09;。 引入&#xff1a; 若要解决选择类的问题&#xff0c;打分的方式最为常用——即采用权重表&#xff1a; 指标权重选择1选择2..…

模板偏特化 (Partial Specialization)

C 模板偏特化 (Partial Specialization) 模板偏特化允许为模板的部分参数或特定类型模式提供定制实现&#xff0c;是 静态多态&#xff08;Static Polymorphism&#xff09; 的核心机制之一。以下通过代码示例和底层原理&#xff0c;全面解析模板偏特化的实现规则、匹配优先级…

sql 根据时间范围获取每日,每月,年月的模版数据

1&#xff1a;获取每日模版数据&#xff08;参数也支持跨年&#xff09; SELECT a.selected_date cdate FROM(SELECT adddate(1970-01-01,t4.i * 10000 t3.i * 1000 t2.i * 100 t1.i * 10 t0.i) selected_dateFROM( SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELEC…

windows上的RagFlow+ollama知识库本地部署

一、 docker的安装与部署 1. 下载Docker Desktop 访问Docker官网并下载适用于Windows的Docker Desktop安装程序。 RagFlow对docker的要求: Docker ≥ 24.0.0 & Docker Compose ≥ v2.26. docker 下载地址: https://www.docker.com/ Get Docker | Docker Docs 如下图所…

多模态大语言模型arxiv论文略读(三十四)

SHIELD : An Evaluation Benchmark for Face Spoofing and Forgery Detection with Multimodal Large Language Models ➡️ 论文标题&#xff1a;SHIELD : An Evaluation Benchmark for Face Spoofing and Forgery Detection with Multimodal Large Language Models ➡️ 论文…

Unity InputSystem触摸屏问题

最近把Unity打包后的windows软件放到windows触摸屏一体机上测试&#xff0c;发现部分屏幕触摸点击不了按钮&#xff0c;测试了其他应用程序都正常。 这个一体机是这样的&#xff0c;一个电脑机箱&#xff0c;外接一个可以触摸的显示屏&#xff0c;然后UGUI的按钮就间歇性点不了…

AI打开潘多拉魔盒?当深度伪造成为虚假信息的核动力引擎

引言&#xff1a;虚假信息——数字时代的“隐形武器” 在人工智能&#xff08;AI&#xff09;与社交媒体深度融合的今天&#xff0c;虚假信息&#xff08;Disinformation&#xff09;已成为全球社会面临的最严峻挑战之一。 source: Gartner.(2024). 2025 Top Strategic Techno…