Files
klp-oa/klp-job/src/main/java/com/klp/job/service/SampleService.java

350 lines
12 KiB
Java
Raw Normal View History

2025-07-17 18:07:48 +08:00
package com.klp.job.service;
2021-12-21 10:15:12 +08:00
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
/**
* XxlJob开发示例Bean模式
* <p>
* 开发步骤
* 1任务开发在Spring Bean实例中开发Job方法
* 2注解配置为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")"注解value值对应的是调度中心新建任务的JobHandler属性的值
* 3执行日志需要通过 "XxlJobHelper.log" 打印执行日志
* 4任务结果默认任务结果为 "成功" 状态不需要主动设置如有诉求比如设置任务结果为失败可以通过 "XxlJobHelper.handleFail/handleSuccess" 自主设置任务结果
*
* @author xuxueli 2019-12-11 21:52:51
*/
@Slf4j
@Service
public class SampleService {
/**
* 1简单任务示例Bean模式
*/
@XxlJob("demoJobHandler")
public void demoJobHandler() throws Exception {
XxlJobHelper.log("XXL-JOB, Hello World.");
for (int i = 0; i < 5; i++) {
XxlJobHelper.log("beat at:" + i);
}
// default success
}
/**
* 2分片广播任务
*/
@XxlJob("shardingJobHandler")
public void shardingJobHandler() throws Exception {
// 分片参数
int shardIndex = XxlJobHelper.getShardIndex();
int shardTotal = XxlJobHelper.getShardTotal();
XxlJobHelper.log("分片参数:当前分片序号 = {}, 总分片数 = {}", shardIndex, shardTotal);
// 业务逻辑
for (int i = 0; i < shardTotal; i++) {
if (i == shardIndex) {
XxlJobHelper.log("第 {} 片, 命中分片开始处理", i);
} else {
XxlJobHelper.log("第 {} 片, 忽略", i);
}
}
}
/**
* 3命令行任务
*/
@XxlJob("commandJobHandler")
public void commandJobHandler() throws Exception {
String command = XxlJobHelper.getJobParam();
int exitValue = -1;
BufferedReader bufferedReader = null;
try {
// command process
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command(command);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
//Process process = Runtime.getRuntime().exec(command);
BufferedInputStream bufferedInputStream = new BufferedInputStream(process.getInputStream());
bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));
// command log
String line;
while ((line = bufferedReader.readLine()) != null) {
XxlJobHelper.log(line);
}
// command exit
process.waitFor();
exitValue = process.exitValue();
} catch (Exception e) {
XxlJobHelper.log(e);
} finally {
if (bufferedReader != null) {
bufferedReader.close();
}
}
if (exitValue == 0) {
// default success
} else {
XxlJobHelper.handleFail("command exit value(" + exitValue + ") is failed");
}
}
/**
* 4跨平台Http任务
* 参数示例
* "url: http://www.baidu.com\n" +
* "method: get\n" +
* "data: content\n";
*/
@XxlJob("httpJobHandler")
public void httpJobHandler() throws Exception {
// param parse
String param = XxlJobHelper.getJobParam();
if (param == null || param.trim().length() == 0) {
XxlJobHelper.log("param[" + param + "] invalid.");
XxlJobHelper.handleFail();
return;
}
String[] httpParams = param.split("\n");
String url = null;
String method = null;
String data = null;
for (String httpParam : httpParams) {
if (httpParam.startsWith("url:")) {
url = httpParam.substring(httpParam.indexOf("url:") + 4).trim();
}
if (httpParam.startsWith("method:")) {
method = httpParam.substring(httpParam.indexOf("method:") + 7).trim().toUpperCase();
}
if (httpParam.startsWith("data:")) {
data = httpParam.substring(httpParam.indexOf("data:") + 5).trim();
}
}
// param valid
if (url == null || url.trim().length() == 0) {
XxlJobHelper.log("url[" + url + "] invalid.");
XxlJobHelper.handleFail();
return;
}
if (method == null || !Arrays.asList("GET", "POST").contains(method)) {
XxlJobHelper.log("method[" + method + "] invalid.");
XxlJobHelper.handleFail();
return;
}
boolean isPostMethod = method.equals("POST");
// request
HttpURLConnection connection = null;
BufferedReader bufferedReader = null;
try {
// connection
URL realUrl = new URL(url);
connection = (HttpURLConnection) realUrl.openConnection();
// connection setting
connection.setRequestMethod(method);
connection.setDoOutput(isPostMethod);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setReadTimeout(5 * 1000);
connection.setConnectTimeout(3 * 1000);
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.setRequestProperty("Accept-Charset", "application/json;charset=UTF-8");
// do connection
connection.connect();
// data
if (isPostMethod && data != null && data.trim().length() > 0) {
DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.write(data.getBytes("UTF-8"));
dataOutputStream.flush();
dataOutputStream.close();
}
// valid StatusCode
int statusCode = connection.getResponseCode();
if (statusCode != 200) {
throw new RuntimeException("Http Request StatusCode(" + statusCode + ") Invalid.");
}
// result
bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
StringBuilder result = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
}
String responseMsg = result.toString();
XxlJobHelper.log(responseMsg);
return;
} catch (Exception e) {
XxlJobHelper.log(e);
XxlJobHelper.handleFail();
return;
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (connection != null) {
connection.disconnect();
}
} catch (Exception e2) {
XxlJobHelper.log(e2);
}
}
}
/**
* 5生命周期任务示例任务初始化与销毁时支持自定义相关逻辑
*/
@XxlJob(value = "demoJobHandler2", init = "init", destroy = "destroy")
public void demoJobHandler2() throws Exception {
XxlJobHelper.log("XXL-JOB, Hello World.");
}
public void init() {
log.info("init");
}
public void destroy() {
log.info("destory");
}
2025-12-02 17:58:16 +08:00
/**
* 6成本日计算任务
* 每天凌晨 2 点由调度中心触发负责调用业务系统接口计算前一日成本日报数据
*
* 调度中心建议配置
* - JobHandlercostDailyCalculateJob
* - Cron0 0 2 * * ?
* - 执行参数可选baseUrl=http://127.0.0.1:8080
*/
@XxlJob("costDailyCalculateJob")
public void costDailyCalculateJob() throws Exception {
// 1. 计算前一日日期
java.time.LocalDate calcDate = java.time.LocalDate.now().minusDays(1);
String dateStr = calcDate.toString(); // yyyy-MM-dd
// 2. 解析调度参数,获取业务系统基础地址
String param = XxlJobHelper.getJobParam();
String baseUrl = "http://127.0.0.1:8080"; // 默认本机
if (param != null && !param.trim().isEmpty()) {
// 简单解析形式baseUrl=http://host:port
for (String line : param.split("\n")) {
line = line.trim();
if (line.startsWith("baseUrl=")) {
baseUrl = line.substring("baseUrl=".length()).trim();
}
}
}
// 3. 构造两个调用地址
String urlDaily = baseUrl + "/wms/cost/coil/batchCalculate?calcDate=" + dateStr;
String urlByEnterCoilNo = baseUrl + "/wms/cost/coil/batchCalculateByEnterCoilNo?calcDate=" + dateStr;
XxlJobHelper.log("开始成本日计算calcDate={}, baseUrl={}", dateStr, baseUrl);
// 4. 依次调用两个接口
try {
doPost(urlDaily);
XxlJobHelper.log("调用 batchCalculate 成功: {}", urlDaily);
} catch (Exception e) {
XxlJobHelper.log(e);
XxlJobHelper.handleFail("调用 batchCalculate 失败: " + e.getMessage());
return;
}
try {
doPost(urlByEnterCoilNo);
XxlJobHelper.log("调用 batchCalculateByEnterCoilNo 成功: {}", urlByEnterCoilNo);
} catch (Exception e) {
XxlJobHelper.log(e);
XxlJobHelper.handleFail("调用 batchCalculateByEnterCoilNo 失败: " + e.getMessage());
return;
}
// 默认成功
}
/**
* 简单的 POST 请求工具复用 JDK HttpURLConnection
*/
private void doPost(String url) throws Exception {
HttpURLConnection connection = null;
BufferedReader bufferedReader = null;
try {
URL realUrl = new URL(url);
connection = (HttpURLConnection) realUrl.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setReadTimeout(30 * 1000);
connection.setConnectTimeout(10 * 1000);
connection.setRequestProperty("connection", "Keep-Alive");
connection.connect();
int statusCode = connection.getResponseCode();
if (statusCode != 200) {
throw new RuntimeException("HTTP " + url + " StatusCode(" + statusCode + ") Invalid.");
}
bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
StringBuilder result = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
}
XxlJobHelper.log("调用 {} 返回: {}", url, result.toString());
} finally {
if (bufferedReader != null) {
bufferedReader.close();
}
if (connection != null) {
connection.disconnect();
}
}
}
2021-12-21 10:15:12 +08:00
}