1、引入相关依赖
maven:
com.xuxueli
xxl-job-core
2.2.0
commons-httpclient
commons-httpclient
3.0.1
2、配置参数
yml配置:
xxl:
job:
login:
username: admin # 登录xxl-job的账号密码
password: 123456
admin:
addresses: http://127.0.0.1:8080/xxl-job-admin # xxl-job服务地址
accessToken:
executor:
appname: abcccc # 执行器对应appname
address:
ip:
port: 9999 # 默认9999 可自定义
logpath: /home/zwapp/apache-tomcat-8.5.61/gxjg/gx-hlwcj
logretentiondays: 30
group: 7 # 执行器ID
3、注入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;
@Bean
public 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 execute(String myId) throws Exception {
System.out.println("-----------------------------");
}
}
旧版本
//@JobHandler(value = "demoJobHandler")
//@Component
//@Slf4j
//public class DemoJobHandler extends IJobHandler {
//
// @Override
// public ReturnT execute(String s) throws Exception {
// System.out.println("=====hello world=====");
// return ReturnT.SUCCESS;
// }}