springboot通过http动态操作xxl-job任务
一、maven依赖
<dependency> <groupid>com.squareup.okhttp3</groupid> <artifactid>okhttp</artifactid> <version>3.8.1</version> </dependency> <dependency> <groupid>cn.hutool</groupid> <artifactid>hutool-all</artifactid> <version>5.6.4</version> </dependency> <dependency> <groupid>com.xuxueli</groupid> <artifactid>xxl-job-core</artifactid> <version>2.2.0</version> </dependency> <dependency> <groupid>org.projectlombok</groupid> <artifactid>lombok</artifactid> <version>1.18.20</version> </dependency>
二、配置文件
xxl: job: login: address: http://192.168.31.91:18080/xxl-job-admin username: admin password: 123456
三、xxl-job实体类
xxljobactuatormanagerinfo
@data @noargsconstructor @allargsconstructor public class xxljobactuatormanagerinfo { private integer recordsfiltered; private integer recordstotal; private list<xxljobgroup> data; }
xxljobgroup
@data @noargsconstructor @allargsconstructor public class xxljobgroup { private int id; private string appname; private string title; private int addresstype; // 执行器地址类型:0=自动注册、1=手动录入 private string addresslist; // 执行器地址列表,多地址逗号分隔(手动录入) private date updatetime; // registry list private list<string> registrylist; // 执行器地址列表(系统注册) public list<string> getregistrylist() { if (addresslist!=null && addresslist.trim().length()>0) { registrylist = new arraylist<string>(arrays.aslist(addresslist.split(","))); } return registrylist; } }
xxljobinfo
@data @noargsconstructor @allargsconstructor public class xxljobinfo { private int id; // 主键id private int jobgroup; // 执行器主键id private string jobdesc; private string jobcron; //corn表达式 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.gluetypeenum private 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; // 下次调度时间 }
xxljobresponseinfo
@data @noargsconstructor @allargsconstructor public class xxljobresponseinfo { private integer code; private string msg; private string content; }
xxljobtaskmanagerinfo
@data @noargsconstructor @allargsconstructor public class xxljobtaskmanagerinfo { private integer recordsfiltered; private integer recordstotal; private list<xxljobinfo> data; }
四、工具类
httpclientconfig
@data @noargsconstructor @allargsconstructor public class httpclientconfig { private string url; private string username; private string password; private string oauthtoken; private int connectiontimeout = 60000; private int requesttimeout = 60000; private int websocketpinginterval; private int maxconcurrentrequestsperhost = 30; private int maxconnection = 40; private string httpproxy; private string httpsproxy; private string proxyusername; private string proxypassword; private string useragent; private tlsversion[] tlsversions = new tlsversion[]{tls_1_2}; private string[] noproxy; public static final string http_protocol_prefix = "http://"; public static final string https_protocol_prefix = "https://"; }
httpclientutils
package com.mye.xxljobtest.util; import okhttp3.*; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.http.httpmethod; import org.springframework.util.collectionutils; import org.springframework.util.stringutils; import java.io.ioexception; import java.net.inetsocketaddress; import java.net.malformedurlexception; import java.net.proxy; import java.net.url; import java.util.arrays; import java.util.map; import java.util.concurrent.timeunit; import static okhttp3.connectionspec.cleartext; public class httpclientutils { private static final logger logger = loggerfactory.getlogger(httpclientutils.class); /** * json传输方式 */ private static final mediatype json = mediatype.parse("application/json; charset=utf-8"); private static volatile okhttpclient client; public static headers dologinrequest(httpclientconfig config, map<string, string> params) { try { okhttpclient client = getinstance(config); formbody.builder builder = new formbody.builder(); for (map.entry<string, string> param : params.entryset()) { builder.add(param.getkey(), param.getvalue()); } formbody formbody = builder.build(); request request = new request.builder().url(config.geturl()).post(formbody).build(); response response = client.newcall(request).execute(); if (response.issuccessful() && response.body() != null) { system.out.println(jsonutil.objecttojson(response)); return response.headers(); } else if (response.body() != null){ return null; } } catch (ioexception e) { e.printstacktrace(); } return null; } public static string doformrequest(httpclientconfig config, map<string, string> params, string cookie) { try { okhttpclient client = getinstance(config); formbody.builder builder = new formbody.builder(); for (map.entry<string, string> param : params.entryset()) { builder.add(param.getkey(), param.getvalue()); } formbody formbody = builder.build(); request request = new request.builder().url(config.geturl()).header("cookie", cookie).post(formbody).build(); response response = client.newcall(request).execute(); if (response.issuccessful() && response.body() != null) { system.out.println(jsonutil.objecttojson(response)); return response.body().string(); } else if (response.body() != null){ return response.body().string(); } } catch (ioexception e) { e.printstacktrace(); } return null; } public static string dorequest(httpclientconfig config, httpmethod method, map<string, string> headers, string body) { try { okhttpclient client = getinstance(config); //创建请求 requestbody requestbody = requestbody.create(json, stringutils.isempty(body) ? "" : body); request.builder builder = new request.builder(); if (!collectionutils.isempty(headers)) { logger.info("headers : " + headers); builder.headers(headers.of(headers)); } request request = builder.method(method.name(), requestbody).url(config.geturl()).build(); response response = client.newcall(request).execute(); if (response.issuccessful() && response.body() != null) { return response.body().string(); } else if (response.body() != null){ return response.body().string(); } } catch (ioexception e) { e.printstacktrace(); } return null; } /** * 双重检查单例 * @param config okhttpclient配置 * @return okhttpclient */ public static okhttpclient getinstance(httpclientconfig config) { if (client == null) { synchronized (okhttpclient.class) { if (client == null) { client = createhttpclient(config); } } } //拿到client之后把认证信息重新加一遍 client.newbuilder().addinterceptor(chain -> { request request = chain.request(); if (stringutils.hastext(config.getusername()) && stringutils.hastext(config.getpassword())) { request authreq = chain.request().newbuilder().addheader("authorization", credentials.basic(config.getusername(), config.getpassword())).build(); return chain.proceed(authreq); } else if (stringutils.hastext( config.getoauthtoken())) { request authreq = chain.request().newbuilder().addheader("authorization", "bearer " + config.getoauthtoken()).build(); return chain.proceed(authreq); } return chain.proceed(request); }); return client; } private static okhttpclient createhttpclient(final httpclientconfig config) { try { okhttpclient.builder httpclientbuilder = new okhttpclient.builder(); httpclientbuilder.followredirects(true); httpclientbuilder.followsslredirects(true); if (config.getconnectiontimeout() > 0) { httpclientbuilder.connecttimeout(config.getconnectiontimeout(), timeunit.milliseconds); } if (config.getrequesttimeout() > 0) { httpclientbuilder.readtimeout(config.getrequesttimeout(), timeunit.milliseconds); } if (config.getwebsocketpinginterval() > 0) { httpclientbuilder.pinginterval(config.getwebsocketpinginterval(), timeunit.milliseconds); } if (config.getmaxconcurrentrequestsperhost() > 0) { dispatcher dispatcher = new dispatcher(); dispatcher.setmaxrequestsperhost(config.getmaxconcurrentrequestsperhost()); httpclientbuilder.dispatcher(dispatcher); } if (config.getmaxconnection() > 0) { connectionpool connectionpool = new connectionpool(config.getmaxconnection(), 60, timeunit.seconds); httpclientbuilder.connectionpool(connectionpool); } // only check proxy if it's a full url with protocol if (config.geturl().tolowercase().startswith(httpclientconfig.http_protocol_prefix) || config.geturl().startswith(httpclientconfig.https_protocol_prefix)) { try { url proxyurl = getproxyurl(config); if (proxyurl != null) { httpclientbuilder.proxy(new proxy(proxy.type.http, new inetsocketaddress(proxyurl.gethost(), proxyurl.getport()))); if (config.getproxyusername() != null) { httpclientbuilder.proxyauthenticator((route, response) -> { string credential = credentials.basic(config.getproxyusername(), config.getproxypassword()); return response.request().newbuilder().header("proxy-authorization", credential).build(); }); } } } catch (malformedurlexception e) { throw new illegalargumentexception("invalid proxy server configuration", e); } } if (config.getuseragent() != null && !config.getuseragent().isempty()) { httpclientbuilder.addnetworkinterceptor(chain -> { request agent = chain.request().newbuilder().header("user-agent", config.getuseragent()).build(); return chain.proceed(agent); }); } if (config.gettlsversions() != null && config.gettlsversions().length > 0) { connectionspec spec = new connectionspec.builder(connectionspec.modern_tls) .tlsversions(config.gettlsversions()) .build(); httpclientbuilder.connectionspecs(arrays.aslist(spec, cleartext)); } return httpclientbuilder.build(); } catch (exception e) { throw new illegalargumentexception("创建okhttpclient错误", e); } } private static url getproxyurl(httpclientconfig config) throws malformedurlexception { url master = new url(config.geturl()); string host = master.gethost(); if (config.getnoproxy() != null) { for (string noproxy : config.getnoproxy()) { if (host.endswith(noproxy)) { return null; } } } string proxy = config.gethttpsproxy(); string http = "http"; if (http.equals(master.getprotocol())) { proxy = config.gethttpproxy(); } if (proxy != null) { return new url(proxy); } return null; } }
xxljobapiutils
package com.mye.xxljobtest.util; import cn.hutool.core.collection.collectionutil; import cn.hutool.core.convert.convert; import cn.hutool.core.util.objectutil; import cn.hutool.json.jsonutil; import com.mye.xxljobtest.jobcore.*; import okhttp3.headers; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.beans.factory.annotation.value; import org.springframework.http.httpstatus; import org.springframework.stereotype.component; import java.util.hashmap; import java.util.list; import java.util.map; /** * xxl-job api 操作工具类 * @author hl * @date 2022/8/1 14:05 */ @component public class xxljobapiutils { private static final logger logger = loggerfactory.getlogger(xxljobapiutils.class); @value("${xxl.job.login.address}") private string xxljobloginaddress; @value("${xxl.job.login.username}") private string xxljobloginusername; @value("${xxl.job.login.password}") private string xxljobloginpassword; /** * 启动xxl-job任务管理 * @param taskid 任务管理id */ public void starttask(integer taskid){ //获取登录cookie httpclientconfig clientconfig = new httpclientconfig(); string cookie = logintaskcenter(clientconfig); //创建参数 map<string, string> form = new hashmap<>(); form.put("id", "" + taskid); clientconfig.seturl(xxljobloginaddress + "/jobinfo/start"); string result = httpclientutils.doformrequest(clientconfig, form, cookie); xxljobresponseinfo info = jsonutil.tobean(jsonutil.parseobj(result), xxljobresponseinfo.class); if (objectutil.isnull(info) || info.getcode() != httpstatus.ok.value()){ logger.error(info.getmsg(),new runtimeexception()); } } /** * 删除 xxl-job任务管理 * @param id 任务id */ public void deletetask(integer id){ //获取登录cookie httpclientconfig clientconfig = new httpclientconfig(); string cookie = logintaskcenter(clientconfig); //创建任务管理参数 map<string, string> form = new hashmap<>(); form.put("id", id + ""); clientconfig.seturl(xxljobloginaddress + "/jobinfo/remove"); string result = httpclientutils.doformrequest(clientconfig, form, cookie); xxljobresponseinfo info = jsonutil.tobean(jsonutil.parseobj(result), xxljobresponseinfo.class); if (objectutil.isnull(info) || info.getcode() != httpstatus.ok.value()){ logger.error(info.getmsg(),new runtimeexception()); } } /** * 编辑 xxl-job任务管理 * @param xxljobinfo 查询参数 */ public void edittask(xxljobinfo xxljobinfo){ //获取登录cookie httpclientconfig clientconfig = new httpclientconfig(); string cookie = logintaskcenter(clientconfig); //创建任务管理参数 map<string, string> form = new hashmap<>(); form.put("id",xxljobinfo.getid() + ""); //注意这里需要先创建执行器,然后拿到执行器的id赋值给jobgroup form.put("jobgroup", xxljobinfo.getjobgroup() + ""); form.put("jobdesc", xxljobinfo.getjobdesc()); form.put("executorroutestrategy", "round"); form.put("jobcron", xxljobinfo.getjobcorn()); form.put("gluetype", "bean"); form.put("executorhandler", xxljobinfo.getexecutorhandler()); form.put("executorblockstrategy", "serial_execution"); form.put("author", "mye"); clientconfig.seturl(xxljobloginaddress + "/jobinfo/update"); string result = httpclientutils.doformrequest(clientconfig, form, cookie); xxljobresponseinfo info = jsonutil.tobean(jsonutil.parseobj(result), xxljobresponseinfo.class); if (objectutil.isnull(info) || info.getcode() != httpstatus.ok.value()){ logger.error(info.getmsg(),new runtimeexception()); } } /** * 查询所有的task * @param xxljobinfo * @return */ public xxljobtaskmanagerinfo selectalltask(xxljobinfo xxljobinfo) { //获取登录cookie httpclientconfig clientconfig = new httpclientconfig(); string cookie = logintaskcenter(clientconfig); //创建任务管理参数 map<string, string> form = new hashmap<>(); form.put("jobgroup", xxljobinfo.getjobgroup() + ""); form.put("triggerstatus", "-1"); clientconfig.seturl(xxljobloginaddress + "/jobinfo/pagelist"); string result = httpclientutils.doformrequest(clientconfig, form, cookie); return jsonutil.tobean(jsonutil.parseobj(result), xxljobtaskmanagerinfo.class); } /** * 查询 xxl-job任务管理 * @param xxljobinfo 查询参数 */ public xxljobtaskmanagerinfo selecttask(xxljobinfo xxljobinfo){ //获取登录cookie httpclientconfig clientconfig = new httpclientconfig(); string cookie = logintaskcenter(clientconfig); //创建任务管理参数 map<string, string> form = new hashmap<>(); form.put("jobgroup", xxljobinfo.getjobgroup() + ""); form.put("jobdesc", xxljobinfo.getjobdesc()); form.put("executorhandler", xxljobinfo.getexecutorhandler()); form.put("author", xxljobinfo.getauthor()); form.put("triggerstatus", "-1"); clientconfig.seturl(xxljobloginaddress + "/jobinfo/pagelist"); string result = httpclientutils.doformrequest(clientconfig, form, cookie); xxljobtaskmanagerinfo info = jsonutil.tobean(jsonutil.parseobj(result), xxljobtaskmanagerinfo.class); if (objectutil.isnull(info) || collectionutil.isempty(info.getdata())){ logger.error("xxl-job任务管理不存在",new runtimeexception()); } return info; } /** * 创建任务管理 * @param xxljobinfo 创建参数 */ public xxljobresponseinfo createtask(xxljobinfo xxljobinfo){ //获取登录cookie httpclientconfig clientconfig = new httpclientconfig(); string cookie = logintaskcenter(clientconfig); //创建任务管理参数 map<string, string> form = new hashmap<>(); form.put("jobgroup", xxljobinfo.getjobgroup() + ""); form.put("jobdesc", xxljobinfo.getjobdesc()); form.put("executorroutestrategy", "round"); form.put("jobcron", xxljobinfo.getjobcorn()); form.put("gluetype", "bean"); form.put("executorhandler", xxljobinfo.getexecutorhandler()); form.put("executorblockstrategy", "serial_execution"); form.put("author", "mye"); //创建任务管理 clientconfig.seturl(xxljobloginaddress + "/jobinfo/add"); string result = httpclientutils.doformrequest(clientconfig, form, cookie); xxljobresponseinfo info = jsonutil.tobean(jsonutil.parseobj(result), xxljobresponseinfo.class); if (objectutil.isnull(info) || info.getcode() != httpstatus.ok.value()){ logger.error(info.getmsg(),new runtimeexception()); } return info; } /** * 删除执行器 */ public void deleteactuator(xxljobgroup xxljobgroup) { //获取登录cookie httpclientconfig clientconfig = new httpclientconfig(); string cookie = logintaskcenter(clientconfig); //创建查询执行器管理器参数 map<string, string> form = new hashmap<>(); form.put("id", xxljobgroup.getid() + ""); //创建执行器管理器地址 clientconfig.seturl(xxljobloginaddress + "/jobgroup/remove"); string result = httpclientutils.doformrequest(clientconfig, form, cookie); xxljobresponseinfo info = jsonutil.tobean(jsonutil.parseobj(result), xxljobresponseinfo.class); if (objectutil.isnull(info) || info.getcode() != httpstatus.ok.value()) { logger.error(info.getmsg(), new runtimeexception()); } } /** * 编辑执行器 */ public void editactuator(xxljobgroup xxljobgroup){ //获取登录cookie httpclientconfig clientconfig = new httpclientconfig(); string cookie = logintaskcenter(clientconfig); //创建查询执行器管理器参数 map<string, string> form = new hashmap<>(); form.put("appname", xxljobgroup.getappname()); form.put("title", xxljobgroup.gettitle()); form.put("addresstype", xxljobgroup.getaddresstype() + ""); form.put("id", xxljobgroup.getid() + ""); //创建执行器管理器地址 clientconfig.seturl(xxljobloginaddress + "/jobgroup/update"); string result = httpclientutils.doformrequest(clientconfig, form, cookie); xxljobresponseinfo info = jsonutil.tobean(jsonutil.parseobj(result), xxljobresponseinfo.class); if (objectutil.isnull(info) || info.getcode() != httpstatus.ok.value()){ logger.error(info.getmsg(),new runtimeexception()); } } /** * 查询执行器 (appname 和 title 都是模糊查询) * @param xxljobgroup xxljobgroup * @return xxljobgroup 集合 */ public list<xxljobgroup> selectactuator(xxljobgroup xxljobgroup){ //获取登录cookie httpclientconfig clientconfig = new httpclientconfig(); string cookie = logintaskcenter(clientconfig); //创建查询执行器管理器参数 map<string, string> form = new hashmap<>(); form.put("appname", xxljobgroup.getappname()); form.put("title", xxljobgroup.gettitle()); //创建执行器管理器地址 clientconfig.seturl(xxljobloginaddress + "/jobgroup/pagelist"); string result = httpclientutils.doformrequest(clientconfig, form, cookie); xxljobactuatormanagerinfo info = jsonutil.tobean(jsonutil.parseobj(result), xxljobactuatormanagerinfo.class); if (collectionutil.isempty(info.getdata())){ throw new runtimeexception("该执行器管理器不存在:" + xxljobgroup.getappname()); } return info.getdata(); } /** * 创建执行器 * * @param xxljobgroup 创建参数 */ public xxljobresponseinfo createactuator(xxljobgroup xxljobgroup) { //获取登录cookie httpclientconfig clientconfig = new httpclientconfig(); string cookie = logintaskcenter(clientconfig); //创建执行器管理器参数 map<string, string> form = new hashmap<>(); form.put("appname", xxljobgroup.getappname()); form.put("title", xxljobgroup.gettitle()); form.put("addresstype", xxljobgroup.getaddresstype() + ""); //创建执行器管理器地址 clientconfig.seturl(xxljobloginaddress + "/jobgroup/save"); string result = httpclientutils.doformrequest(clientconfig, form, cookie); xxljobresponseinfo info = jsonutil.tobean(jsonutil.parseobj(result), xxljobresponseinfo.class); if (objectutil.isnull(info) || info.getcode() != httpstatus.ok.value()){ logger.error(info.getmsg(),new runtimeexception()); } return info; } /** * 登录任务调度平台 * * @param clientconfig clientconfig * @return cookie */ public string logintaskcenter(httpclientconfig clientconfig) { map<string, string> loginform = new hashmap<>(); clientconfig.seturl(xxljobloginaddress + "/login"); clientconfig.setusername(xxljobloginusername); clientconfig.setpassword(xxljobloginpassword); loginform.put("username", xxljobloginusername); loginform.put("password", xxljobloginpassword); headers headers = httpclientutils.dologinrequest(clientconfig, loginform); assert headers != null; return headers.get("set-cookie"); } }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论