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.pswp.cn/pingmian/78073.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/78073.shtml
英文地址,請注明出處:http://en.pswp.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…