當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Springboot整合xxl-job实现任务自定义定时任务
生活随笔
收集整理的這篇文章主要介紹了
Springboot整合xxl-job实现任务自定义定时任务
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、引入相關依賴
maven:<dependency><groupId>com.xuxueli</groupId><artifactId>xxl-job-core</artifactId><version>2.2.0</version></dependency><dependency><groupId>commons-httpclient</groupId><artifactId>commons-httpclient</artifactId><version>3.0.1</version></dependency>2、配置參數
yml配置: xxl:job:login:username: admin # 登錄xxl-job的賬號密碼password: 123456admin:addresses: http://127.0.0.1:8080/xxl-job-admin # xxl-job服務地址accessToken:executor:appname: abcccc # 執行器對應appnameaddress:ip:port: 9999 # 默認9999 可自定義logpath: /home/zwapp/apache-tomcat-8.5.61/gxjg/gx-hlwcjlogretentiondays: 30group: 7 # 執行器ID3、注入spring容器
package cn.com.thtf.hlwcj.config;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;/*** @author bo*/ @SuppressWarnings("ALL") @Configuration public class XxlJobConfig {private Logger logger = LoggerFactory.getLogger(XxlJobConfig.class);@Value("${xxl.job.admin.addresses}")private String adminAddresses;@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.accessToken}")private String accessToken;@Value("${xxl.job.executor.logpath}")private String logPath;@Value("${xxl.job.executor.logretentiondays}")private int logRetentionDays;@Beanpublic 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;} }4、調用xxl-job服務工具類? 新版會有登錄校驗? 見XxlJobUtil1
XxlJobUtil:
package cn.com.thtf.hlwcj.util;import cn.com.thtf.hlwcj.config.CustomConstants; import cn.com.thtf.hlwcj.module.GxHlwcjScanFrequencyEntity; import cn.com.thtf.hlwcj.module.XxlJobInfo; import cn.com.thtf.hlwcj.vo.UpdateNetDataGatherTaskVO; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.google.common.base.Joiner; import com.xxl.job.core.biz.model.ReturnT; import com.xxl.job.core.util.DateUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.lang3.StringUtils; import org.apache.http.entity.ContentType; import org.yaml.snakeyaml.util.UriEncoder;import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Date; import java.util.List;/**** //todo 新增和更新都是表單提交** @author bo* @date 2021/4/19* @description*/ @Slf4j public class XxlJobUtil {/*** 新增/編輯任務* @param url* @param param* @return* @throws HttpException* @throws IOException*/public static JSONObject addJob(String url, String param) throws Exception{PostMethod post = new PostMethod(url + "/jobinfo/add");JSONObject result = getXxlJobData(param, post);return result;}public static JSONObject updateJob(String url, String param) throws IOException {PostMethod post = new PostMethod(url + "/jobinfo/update");JSONObject result = getXxlJobData(param, post);return result;}/*** 刪除任務* @param url* @param jobId* @return* @throws HttpException* @throws IOException*/public static JSONObject deleteJob(String url,int jobId) throws HttpException, IOException {String param = "id=" + jobId;PostMethod post = new PostMethod(url + "/jobinfo/remove");JSONObject result = getXxlJobData(param, post);return result;}/*** 開始任務** @param url* @param jobId* @return* @throws HttpException* @throws IOException*/public static JSONObject startJob(String url, int jobId) throws HttpException, IOException {String param = "id=" + jobId;PostMethod post = new PostMethod(url + "/jobinfo/start");JSONObject result = getXxlJobData(param, post);return result;}/*** 停止任務** @param url* @param jobId* @return* @throws HttpException* @throws IOException*/public static JSONObject stopJob(String url, int jobId) throws HttpException, IOException {String param = "id=" + jobId;PostMethod post = new PostMethod(url + "/jobinfo/stop");JSONObject result = getXxlJobData(param, post);return result;}/*** 手動執行任務** @param url* @param param* @return* @throws HttpException* @throws IOException*/public static JSONObject executeJob(String url, String param) throws HttpException, IOException {PostMethod post = new PostMethod(url + "/jobinfo/trigger");JSONObject result = getXxlJobData(param, post);return result;}/*** 獲取任務列表** @param url* @param param* @return* @throws IOException*/public static JSONObject getTaskList(String url, String param) throws IOException {PostMethod post = new PostMethod(url + "/jobinfo/pageList");JSONObject result = getXxlJobData(param, post);return result;}/*** 獲取任務下一次執行時間** @param url* @param param* @return* @throws IOException*/public static JSONObject getTaskNextTriggerTime(String url, String param) throws IOException {PostMethod post = new PostMethod(url + "/jobinfo/nextTriggerTime");JSONObject result = getXxlJobData(param, post);return result;}public static String getTaskNextTime(String url, String cron) {try {if (StringUtils.isNotBlank(cron)) {String taskNestTimeParams = Joiner.on("&").join("scheduleType=CRON","scheduleConf=" + UriEncoder.encode(cron));JSONObject response = getTaskNextTriggerTime(url, taskNestTimeParams);if (response.containsKey(CustomConstants.REQUEST_CODE) && 200 == (Integer) response.get(CustomConstants.REQUEST_CODE)) {JSONArray content = response.getJSONArray("content");return content.getString(0);}}} catch (Exception e) {e.printStackTrace();}return StringUtils.EMPTY;}/*** 根據xxl-appname獲取對應id** @param url* @param appnameParam* @return* @throws HttpException* @throws IOException*/public static JSONObject getAppNameIdByAppname(String url, String appnameParam) throws HttpException, IOException {String param = "appnameParam=" + appnameParam;PostMethod post = new PostMethod(url + "/jobgroup/getAppNameIdByAppname");JSONObject result = getXxlJobData(param, post);return result;}private static JSONObject getXxlJobData(String param, PostMethod post) throws IOException {HttpClient httpClient = new HttpClient();post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");RequestEntity requestEntity = new StringRequestEntity(param, ContentType.APPLICATION_JSON.getMimeType(), "utf-8");post.setRequestEntity(requestEntity);httpClient.executeMethod(post);JSONObject result = new JSONObject();result = getJsonObject(post, result);return result;}private static JSONObject getJsonObject(HttpMethod get, JSONObject result) throws IOException {InputStream inputStream = get.getResponseBodyAsStream();BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));StringBuffer stringBuffer = new StringBuffer();String str = "";while ((str = br.readLine()) != null) {stringBuffer.append(str);}if (get.getStatusCode() == 200) {/*** 使用此方式會出現* Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.* 異常* String responseBodyAsString = get.getResponseBodyAsString();* result = JSONObject.parseObject(responseBodyAsString);*/result = JSONObject.parseObject(stringBuffer.toString());} else {try { // result = JSONObject.parseObject(get.getResponseBodyAsString());result = JSONObject.parseObject(stringBuffer.toString());} catch (Exception e) {result.put("error", stringBuffer.toString());}}return result;}}XxlJobUtil1:
import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpResponse; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod;import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader;@Slf4j public class XxlJobUtil1 {//自己本地測試的時候,直接把管理頁的cookie放在這里就能用,偷個懶private static String cookie="xxljob_adminlte_settings=on; XXL_JOB_LOGIN_IDENTITY=7b226964223a312c22757365726e616d65223a2261646d696e222c2270617373776f7264223a226531306164633339343962613539616262653536653035376632306638383365222c22726f6c65223a312c227065726d697373696f6e223a6e756c6c7d";/*** 新增/編輯任務* @param url* @param requestInfo* @return* @throws HttpException* @throws IOException*/public static JSONObject addJob(String url, JSONObject requestInfo) throws HttpException, IOException {String path = "/jobinfo/add";String targetPath=url+path;cookie=getCookie();HttpResponse response = HttpRequest.post(targetPath).form(requestInfo).cookie(cookie).execute();JSONObject jsonObject = JSON.parseObject(response.body());return jsonObject;}public static JSONObject updateJob(String url, JSONObject requestInfo) throws HttpException, IOException {String path = "/jobinfo/update";String targetPath=url+path;cookie=getCookie();HttpResponse response = HttpRequest.post(targetPath).form(requestInfo).cookie(cookie).execute();JSONObject jsonObject = JSON.parseObject(response.body());return jsonObject;}/*** 刪除任務* @param url* @param id* @return* @throws HttpException* @throws IOException*/public static JSONObject deleteJob(String url,int id) throws HttpException, IOException {String path = "/jobinfo/remove?id=" + id;String targetPath=url+path;cookie=getCookie();HttpResponse response = HttpRequest.post(targetPath).cookie(cookie).execute();JSONObject jsonObject = JSON.parseObject(response.body());return jsonObject;}/*** 開始任務* @param url* @param id* @return* @throws HttpException* @throws IOException*/public static JSONObject startJob(String url,int id) throws HttpException, IOException {String path = "/jobinfo/start?id="+id;String targetPath=url+path;cookie=getCookie();HttpResponse response = HttpRequest.post(targetPath).cookie(cookie).execute();JSONObject jsonObject = JSON.parseObject(response.body());return jsonObject;}/*** 停止任務* @param url* @param id* @return* @throws HttpException* @throws IOException*/public static JSONObject stopJob(String url,int id) throws HttpException, IOException {String path = "/jobinfo/stop?id="+id;String targetPath=url+path;cookie=getCookie();HttpResponse response = HttpRequest.post(targetPath).cookie(cookie).execute();JSONObject jsonObject = JSON.parseObject(response.body());return jsonObject;}/*** 根據xxl-appname獲取對應id* @param url* @param appnameParam* @return* @throws HttpException* @throws IOException*/public static JSONObject getAppNameIdByAppname(String url,String appnameParam) throws HttpException, IOException {String path = "/jobgroup/getAppNameIdByAppname?appnameParam="+appnameParam;String targetPath=url+path;cookie=getCookie();HttpResponse response = HttpRequest.post(targetPath).cookie(cookie).execute();JSONObject jsonObject = JSON.parseObject(response.body());return jsonObject;}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 get, JSONObject result) throws IOException {InputStream inputStream = get.getResponseBodyAsStream();BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));StringBuffer stringBuffer = new StringBuffer();String str = "";while ((str = br.readLine()) != null) {stringBuffer.append(str);}if (get.getStatusCode() == 200) {/*** 使用此方式會出現* Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.* 異常* String responseBodyAsString = get.getResponseBodyAsString();* result = JSONObject.parseObject(responseBodyAsString);*/result = JSONObject.parseObject(stringBuffer.toString());} else {try { // result = JSONObject.parseObject(get.getResponseBodyAsString());result = JSONObject.parseObject(stringBuffer.toString());} catch (Exception e) {result.put("error", stringBuffer.toString());}}return result;}public static String login(String url, String userName, String password) throws HttpException, IOException {String path = "/login?userName="+userName+"&password="+password;String targetUrl = url + path;HttpClient httpClient = new HttpClient();PostMethod get = new PostMethod(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;}/*** @Description 獲取登錄cookie* @Author chengweiping* @Date 2021/4/13 16:39*/public static String getCookie() {return cookie;}public static void setCookie(String cookie) {XxlJobUtil1.cookie = cookie;} }5、執行器代碼,直接處理你的業務就行了
import com.thtf.data.platform.worker.entity.XxlJobInfoEntity; import com.thtf.data.platform.worker.mapper.XxlJobInfoMapper; import com.thtf.data.platform.worker.service.IDataSynService; import com.xxl.job.core.biz.model.ReturnT; import com.xxl.job.core.handler.IJobHandler; import com.xxl.job.core.handler.annotation.XxlJob; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component;import javax.annotation.Resource; import java.sql.Timestamp; import java.util.Date;/*** 1、簡單任務示例(Bean模式)* !!!依賴xxl-job-core版本>=2.3.0時** @author bo*/ @Component @Slf4j public class GxhlwcjJorHandler extends IJobHandler {@XxlJob(value = "HlwcjJobHandler")public ReturnT<String> execute(String myId) throws Exception {System.out.println("-----------------------------");} }舊版本 //@JobHandler(value = "demoJobHandler") //@Component //@Slf4j //public class DemoJobHandler extends IJobHandler { // // @Override // public ReturnT<String> execute(String s) throws Exception { // System.out.println("=====hello world====="); // return ReturnT.SUCCESS; // }}總結
以上是生活随笔為你收集整理的Springboot整合xxl-job实现任务自定义定时任务的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springboot开启jms服务监控j
- 下一篇: 分布式事务原理及实战seata(转自微信