23
xxl-job-executor-samples/pom.xml
Normal file
23
xxl-job-executor-samples/pom.xml
Normal file
@@ -0,0 +1,23 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.xuxueli</groupId>
|
||||
<artifactId>xxl-job</artifactId>
|
||||
<version>3.3.2</version>
|
||||
</parent>
|
||||
<artifactId>xxl-job-executor-samples</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<modules>
|
||||
<module>xxl-job-executor-sample-frameless</module>
|
||||
<module>xxl-job-executor-sample-springboot</module>
|
||||
<module>xxl-job-executor-sample-springboot-ai</module>
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<maven.install.skip>true</maven.install.skip>
|
||||
<maven.deploy.skip>true</maven.deploy.skip>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.xuxueli</groupId>
|
||||
<artifactId>xxl-job-executor-samples</artifactId>
|
||||
<version>3.3.2</version>
|
||||
</parent>
|
||||
<artifactId>xxl-job-executor-sample-frameless</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>${project.artifactId}</name>
|
||||
<description>Example executor project for spring boot.</description>
|
||||
<url>https://www.xuxueli.com/</url>
|
||||
|
||||
|
||||
<dependencies>
|
||||
|
||||
<!-- slf4j -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-reload4j</artifactId>
|
||||
</dependency>
|
||||
<!-- junit -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- xxl-job-core -->
|
||||
<dependency>
|
||||
<groupId>com.xuxueli</groupId>
|
||||
<artifactId>xxl-job-core</artifactId>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.xxl.job.executor.sample.frameless;
|
||||
|
||||
import com.xxl.job.executor.sample.frameless.config.FrameLessXxlJobConfig;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* @author xuxueli 2018-10-31 19:05:43
|
||||
*/
|
||||
public class XxlJobFramelessApplication {
|
||||
private static final Logger logger = LoggerFactory.getLogger(XxlJobFramelessApplication.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
try {
|
||||
// start
|
||||
FrameLessXxlJobConfig.getInstance().initXxlJobExecutor();
|
||||
|
||||
// Blocks until interrupted
|
||||
while (true) {
|
||||
try {
|
||||
TimeUnit.HOURS.sleep(1);
|
||||
} catch (InterruptedException e) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage(), e);
|
||||
} finally {
|
||||
// destroy
|
||||
FrameLessXxlJobConfig.getInstance().destroyXxlJobExecutor();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.xxl.job.executor.sample.frameless.config;
|
||||
|
||||
import com.xxl.job.executor.sample.frameless.jobhandler.SampleXxlJob;
|
||||
import com.xxl.job.core.executor.impl.XxlJobSimpleExecutor;
|
||||
import com.xxl.tool.core.PropTool;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* @author xuxueli 2018-10-31 19:05:43
|
||||
*/
|
||||
public class FrameLessXxlJobConfig {
|
||||
private static final Logger logger = LoggerFactory.getLogger(FrameLessXxlJobConfig.class);
|
||||
|
||||
|
||||
private static final FrameLessXxlJobConfig instance = new FrameLessXxlJobConfig();
|
||||
public static FrameLessXxlJobConfig getInstance() {
|
||||
return instance;
|
||||
}
|
||||
|
||||
|
||||
private XxlJobSimpleExecutor xxlJobExecutor = null;
|
||||
|
||||
/**
|
||||
* init
|
||||
*/
|
||||
public void initXxlJobExecutor() {
|
||||
|
||||
// load executor prop
|
||||
Properties xxlJobProp = PropTool.loadProp("xxl-job-executor.properties");
|
||||
|
||||
// init executor
|
||||
xxlJobExecutor = new XxlJobSimpleExecutor();
|
||||
xxlJobExecutor.setAdminAddresses(xxlJobProp.getProperty("xxl.job.admin.addresses"));
|
||||
xxlJobExecutor.setAccessToken(xxlJobProp.getProperty("xxl.job.admin.accessToken"));
|
||||
xxlJobExecutor.setTimeout(Integer.valueOf(xxlJobProp.getProperty("xxl.job.admin.timeout")));
|
||||
xxlJobExecutor.setEnabled(Boolean.valueOf(xxlJobProp.getProperty("xxl.job.executor.enabled")));
|
||||
xxlJobExecutor.setAppname(xxlJobProp.getProperty("xxl.job.executor.appname"));
|
||||
xxlJobExecutor.setAddress(xxlJobProp.getProperty("xxl.job.executor.address"));
|
||||
xxlJobExecutor.setIp(xxlJobProp.getProperty("xxl.job.executor.ip"));
|
||||
xxlJobExecutor.setPort(Integer.valueOf(xxlJobProp.getProperty("xxl.job.executor.port")));
|
||||
xxlJobExecutor.setLogPath(xxlJobProp.getProperty("xxl.job.executor.logpath"));
|
||||
xxlJobExecutor.setLogRetentionDays(Integer.valueOf(xxlJobProp.getProperty("xxl.job.executor.logretentiondays")));
|
||||
|
||||
// registry job bean
|
||||
xxlJobExecutor.setXxlJobBeanList(Arrays.asList(new SampleXxlJob()));
|
||||
|
||||
// start executor
|
||||
try {
|
||||
xxlJobExecutor.start();
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* destroy
|
||||
*/
|
||||
public void destroyXxlJobExecutor() {
|
||||
if (xxlJobExecutor != null) {
|
||||
xxlJobExecutor.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
package com.xxl.job.executor.sample.frameless.jobhandler;
|
||||
|
||||
import com.xxl.job.core.context.XxlJobHelper;
|
||||
import com.xxl.job.core.handler.annotation.XxlJob;
|
||||
import com.xxl.tool.core.StringTool;
|
||||
import com.xxl.tool.json.GsonTool;
|
||||
import com.xxl.tool.http.HttpTool;
|
||||
import com.xxl.tool.http.http.HttpResponse;
|
||||
import com.xxl.tool.http.http.enums.ContentType;
|
||||
import com.xxl.tool.http.http.enums.Method;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* XxlJob开发示例(Bean模式)
|
||||
*
|
||||
* 开发步骤:
|
||||
* 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
|
||||
*/
|
||||
public class SampleXxlJob {
|
||||
private static final Logger logger = LoggerFactory.getLogger(SampleXxlJob.class);
|
||||
|
||||
|
||||
/**
|
||||
* 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);
|
||||
TimeUnit.SECONDS.sleep(2);
|
||||
}
|
||||
// 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、命令行任务
|
||||
*
|
||||
* 参数示例:"ls -a" 或者 "pwd"
|
||||
*/
|
||||
@XxlJob("commandJobHandler")
|
||||
public void commandJobHandler() throws Exception {
|
||||
String command = XxlJobHelper.getJobParam();
|
||||
int exitValue = -1;
|
||||
|
||||
BufferedReader bufferedReader = null;
|
||||
try {
|
||||
// valid
|
||||
if (command==null || command.trim().isEmpty()) {
|
||||
XxlJobHelper.handleFail("command empty.");
|
||||
return;
|
||||
}
|
||||
|
||||
// command split
|
||||
String[] commandArray = command.split(" ");
|
||||
|
||||
// command process
|
||||
ProcessBuilder processBuilder = new ProcessBuilder();
|
||||
processBuilder.command(commandArray);
|
||||
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任务
|
||||
*
|
||||
* 参数示例:
|
||||
* <pre>
|
||||
* // 1、简单示例:
|
||||
* {
|
||||
* "url": "http://www.baidu.com",
|
||||
* "method": "get",
|
||||
* "data": "hello world"
|
||||
* }
|
||||
*
|
||||
* // 2、完整参数示例:
|
||||
* {
|
||||
* "url": "http://www.baidu.com",
|
||||
* "method": "POST",
|
||||
* "contentType": "application/json",
|
||||
* "headers": {
|
||||
* "header01": "value01"
|
||||
* },
|
||||
* "cookies": {
|
||||
* "cookie01": "value01"
|
||||
* },
|
||||
* "timeout": 3000,
|
||||
* "data": "request body data",
|
||||
* "form": {
|
||||
* "key01": "value01"
|
||||
* },
|
||||
* "auth": "auth data"
|
||||
* }
|
||||
* </pre>
|
||||
*/
|
||||
@XxlJob("httpJobHandler")
|
||||
public void httpJobHandler() throws Exception {
|
||||
|
||||
// param data
|
||||
String param = XxlJobHelper.getJobParam();
|
||||
if (param==null || param.trim().isEmpty()) {
|
||||
XxlJobHelper.log("param["+ param +"] invalid.");
|
||||
|
||||
XxlJobHelper.handleFail();
|
||||
return;
|
||||
}
|
||||
|
||||
// param parse
|
||||
HttpJobParam httpJobParam = null;
|
||||
try {
|
||||
httpJobParam = GsonTool.fromJson(param, HttpJobParam.class);
|
||||
} catch (Exception e) {
|
||||
XxlJobHelper.log(new RuntimeException("HttpJobParam parse error", e));
|
||||
XxlJobHelper.handleFail();
|
||||
return;
|
||||
}
|
||||
|
||||
// param valid
|
||||
if (httpJobParam == null) {
|
||||
XxlJobHelper.log("param parse fail.");
|
||||
XxlJobHelper.handleFail();
|
||||
return;
|
||||
}
|
||||
if (StringTool.isBlank(httpJobParam.getUrl())) {
|
||||
XxlJobHelper.log("url["+ httpJobParam.getUrl() +"] invalid.");
|
||||
XxlJobHelper.handleFail();
|
||||
return;
|
||||
}
|
||||
if (!isValidDomain(httpJobParam.getUrl())) {
|
||||
XxlJobHelper.log("url["+ httpJobParam.getUrl() +"] not allowed.");
|
||||
XxlJobHelper.handleFail();
|
||||
return;
|
||||
}
|
||||
Method method = Method.POST;
|
||||
if (StringTool.isNotBlank(httpJobParam.getMethod())) {
|
||||
Method methodParam = Method.valueOf(httpJobParam.getMethod().toUpperCase());
|
||||
if (methodParam == null) {
|
||||
XxlJobHelper.log("method["+ httpJobParam.getMethod() +"] invalid.");
|
||||
XxlJobHelper.handleFail();
|
||||
return;
|
||||
}
|
||||
method = methodParam;
|
||||
}
|
||||
ContentType contentType = ContentType.JSON;
|
||||
if (StringTool.isNotBlank(httpJobParam.getContentType())) {
|
||||
for (ContentType contentTypeParam : ContentType.values()) {
|
||||
if (contentTypeParam.getValue().equals(httpJobParam.getContentType())) {
|
||||
contentType = contentTypeParam;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (httpJobParam.getTimeout() <= 0) {
|
||||
httpJobParam.setTimeout(3000);
|
||||
}
|
||||
|
||||
// do request
|
||||
try {
|
||||
HttpResponse httpResponse = HttpTool.createRequest()
|
||||
.url(httpJobParam.getUrl())
|
||||
.method(method)
|
||||
.contentType(contentType)
|
||||
.header(httpJobParam.getHeaders())
|
||||
.cookie(httpJobParam.getCookies())
|
||||
.body(httpJobParam.getData())
|
||||
.form(httpJobParam.getForm())
|
||||
.auth(httpJobParam.getAuth())
|
||||
.execute();
|
||||
|
||||
XxlJobHelper.log("StatusCode: " + httpResponse.statusCode());
|
||||
XxlJobHelper.log("Response: <br>" + httpResponse.response());
|
||||
} catch (Exception e) {
|
||||
XxlJobHelper.log(e);
|
||||
XxlJobHelper.handleFail();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* domain white-list, for httpJobHandler
|
||||
*/
|
||||
private static Set<String> DOMAIN_WHITE_LIST = Set.of(
|
||||
"http://www.baidu.com",
|
||||
"http://cn.bing.com"
|
||||
);
|
||||
|
||||
/**
|
||||
* valid if domain is in white-list
|
||||
*/
|
||||
private boolean isValidDomain(String url) {
|
||||
if (url == null || DOMAIN_WHITE_LIST.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
for (String prefix : DOMAIN_WHITE_LIST) {
|
||||
if (url.startsWith(prefix)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/*public static void main(String[] args) {
|
||||
HttpJobParam httpJobParam = new HttpJobParam();
|
||||
httpJobParam.setUrl("http://www.baidu.com");
|
||||
httpJobParam.setMethod(Method.POST.name());
|
||||
httpJobParam.setContentType(ContentType.JSON.getValue());
|
||||
httpJobParam.setHeaders(Map.of("header01", "value01"));
|
||||
httpJobParam.setCookies(Map.of("cookie01", "value01"));
|
||||
httpJobParam.setTimeout(3000);
|
||||
httpJobParam.setData("request body data");
|
||||
httpJobParam.setForm(Map.of("form01", "value01"));
|
||||
httpJobParam.setAuth("auth data");
|
||||
|
||||
logger.info(GsonTool.toJson(httpJobParam));
|
||||
}*/
|
||||
|
||||
/**
|
||||
* http job param
|
||||
*/
|
||||
private static class HttpJobParam{
|
||||
private String url; // 请求 Url
|
||||
private String method; // Method
|
||||
private String contentType; // Content-Type
|
||||
private Map<String, String> headers; // 存储请求头
|
||||
private Map<String, String> cookies; // Cookie(需要格式转换)
|
||||
private int timeout; // 请求超时时间
|
||||
private String data; // 存储请求体
|
||||
private Map<String, String> form; // 存储表单数据
|
||||
private String auth; // 鉴权信息
|
||||
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
public void setUrl(String url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
public String getMethod() {
|
||||
return method;
|
||||
}
|
||||
|
||||
public void setMethod(String method) {
|
||||
this.method = method;
|
||||
}
|
||||
|
||||
public String getContentType() {
|
||||
return contentType;
|
||||
}
|
||||
|
||||
public void setContentType(String contentType) {
|
||||
this.contentType = contentType;
|
||||
}
|
||||
|
||||
public Map<String, String> getHeaders() {
|
||||
return headers;
|
||||
}
|
||||
|
||||
public void setHeaders(Map<String, String> headers) {
|
||||
this.headers = headers;
|
||||
}
|
||||
|
||||
public Map<String, String> getCookies() {
|
||||
return cookies;
|
||||
}
|
||||
|
||||
public void setCookies(Map<String, String> cookies) {
|
||||
this.cookies = cookies;
|
||||
}
|
||||
|
||||
public int getTimeout() {
|
||||
return timeout;
|
||||
}
|
||||
|
||||
public void setTimeout(int timeout) {
|
||||
this.timeout = timeout;
|
||||
}
|
||||
|
||||
public String getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public void setData(String data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public Map<String, String> getForm() {
|
||||
return form;
|
||||
}
|
||||
|
||||
public void setForm(Map<String, String> form) {
|
||||
this.form = form;
|
||||
}
|
||||
|
||||
public String getAuth() {
|
||||
return auth;
|
||||
}
|
||||
|
||||
public void setAuth(String auth) {
|
||||
this.auth = auth;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 5、生命周期任务示例:任务初始化与销毁时,支持自定义相关逻辑;
|
||||
*/
|
||||
@XxlJob(value = "demoJobHandler2", init = "init", destroy = "destroy")
|
||||
public void demoJobHandler2() throws Exception {
|
||||
XxlJobHelper.log("XXL-JOB, Hello World.");
|
||||
}
|
||||
public void init(){
|
||||
logger.info("init");
|
||||
}
|
||||
public void destroy(){
|
||||
logger.info("destroy");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE log4j:configuration PUBLIC "-//log4j/log4j Configuration//EN" "log4j.dtd">
|
||||
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" threshold="null" debug="null">
|
||||
|
||||
<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
|
||||
<param name="Target" value="System.out" />
|
||||
<layout class="org.apache.log4j.PatternLayout">
|
||||
<param name="ConversionPattern" value="%-d{yyyy-MM-dd HH:mm:ss} xxl-job-executor-sample-frameless [%c]-[%t]-[%M]-[%L]-[%p] %m%n"/>
|
||||
</layout>
|
||||
</appender>
|
||||
|
||||
<appender name="FILE" class="org.apache.log4j.DailyRollingFileAppender">
|
||||
<param name="file" value="/data/applogs/xxl-job/xxl-job-executor-sample-frameless.log"/>
|
||||
<param name="append" value="true"/>
|
||||
<param name="encoding" value="UTF-8"/>
|
||||
<layout class="org.apache.log4j.PatternLayout">
|
||||
<param name="ConversionPattern" value="%-d{yyyy-MM-dd HH:mm:ss} xxl-job-executor-sample-frameless [%c]-[%t]-[%M]-[%L]-[%p] %m%n"/>
|
||||
</layout>
|
||||
</appender>
|
||||
|
||||
<root>
|
||||
<level value="INFO" />
|
||||
<appender-ref ref="CONSOLE" />
|
||||
<appender-ref ref="FILE" />
|
||||
</root>
|
||||
|
||||
</log4j:configuration>
|
||||
@@ -0,0 +1,20 @@
|
||||
### xxl-job admin address list, such as "http://address" or "http://address01,http://address02"
|
||||
xxl.job.admin.addresses=http://127.0.0.1:8080/xxl-job-admin
|
||||
### xxl-job access token
|
||||
xxl.job.admin.accessToken=default_token
|
||||
### xxl-job timeout by second, default 3s
|
||||
xxl.job.admin.timeout=3
|
||||
|
||||
### xxl-job executor enable, default true
|
||||
xxl.job.executor.enabled=true
|
||||
### xxl-job executor appname
|
||||
xxl.job.executor.appname=xxl-job-executor-sample
|
||||
### xxl-job executor registry-address: default use address to registry , otherwise use ip:port if address is null
|
||||
xxl.job.executor.address=
|
||||
### xxl-job executor server-info
|
||||
xxl.job.executor.ip=
|
||||
xxl.job.executor.port=9998
|
||||
### xxl-job executor log-path
|
||||
xxl.job.executor.logpath=/data/applogs/xxl-job/jobhandler
|
||||
### xxl-job executor log-retention-days
|
||||
xxl.job.executor.logretentiondays=30
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.xxl.job.executor.sample.frameless.test;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.platform.commons.annotation.Testable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@Testable
|
||||
public class FramelessApplicationTest {
|
||||
private static final Logger logger = LoggerFactory.getLogger(FramelessApplicationTest.class);
|
||||
|
||||
@Test
|
||||
@DisplayName("test1")
|
||||
public void test1(){
|
||||
logger.info("111");
|
||||
Assertions.assertNull( null);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
# base image
|
||||
FROM openjdk:21-jdk-slim
|
||||
|
||||
# maintainer
|
||||
MAINTAINER xuxueli
|
||||
|
||||
# set params
|
||||
ENV PARAMS=""
|
||||
|
||||
# set timezone
|
||||
ENV TZ=PRC
|
||||
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
|
||||
|
||||
# copy jar
|
||||
ADD target/xxl-job-executor-sample-springboot-ai*.jar /app.jar
|
||||
|
||||
# command
|
||||
# log home: -e LOG_HOME=/data/applogs
|
||||
# jvm options: -e JAVA_OPTS="-Xms128m -Xmx128m"
|
||||
# app params: -e PARAMS="--server.port=8080"
|
||||
ENTRYPOINT ["sh","-c","java ${LOG_HOME:+-DLOG_HOME=$LOG_HOME} -jar $JAVA_OPTS /app.jar $PARAMS"]
|
||||
@@ -0,0 +1,70 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.xuxueli</groupId>
|
||||
<artifactId>xxl-job-executor-samples</artifactId>
|
||||
<version>3.3.2</version>
|
||||
</parent>
|
||||
<artifactId>xxl-job-executor-sample-springboot-ai</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>${project.artifactId}</name>
|
||||
<description>Example executor project for spring boot.</description>
|
||||
<url>https://www.xuxueli.com/</url>
|
||||
|
||||
<properties>
|
||||
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- spring-boot-starter-web (spring-webmvc + tomcat) -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- xxl-job-core -->
|
||||
<dependency>
|
||||
<groupId>com.xuxueli</groupId>
|
||||
<artifactId>xxl-job-core</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- spring-ai -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.ai</groupId>
|
||||
<artifactId>spring-ai-starter-model-ollama</artifactId>
|
||||
</dependency>
|
||||
<!-- dify -->
|
||||
<dependency>
|
||||
<groupId>io.github.imfangs</groupId>
|
||||
<artifactId>dify-java-client</artifactId>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.xxl.job.executor;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
/**
|
||||
* @author xuxueli 2018-10-28 00:38:13
|
||||
*/
|
||||
@SpringBootApplication
|
||||
public class XxlJobAIExecutorApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(XxlJobAIExecutorApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.xxl.job.executor.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;
|
||||
|
||||
/**
|
||||
* xxl-job config
|
||||
*
|
||||
* @author xuxueli 2017-04-28
|
||||
*/
|
||||
@Configuration
|
||||
public class XxlJobConfig {
|
||||
private static final Logger logger = LoggerFactory.getLogger(XxlJobConfig.class);
|
||||
|
||||
@Value("${xxl.job.admin.addresses}")
|
||||
private String adminAddresses;
|
||||
|
||||
@Value("${xxl.job.admin.accessToken}")
|
||||
private String accessToken;
|
||||
|
||||
@Value("${xxl.job.admin.timeout}")
|
||||
private int timeout;
|
||||
|
||||
@Value("${xxl.job.executor.enabled}")
|
||||
private Boolean enabled;
|
||||
|
||||
@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.executor.logpath}")
|
||||
private String logPath;
|
||||
|
||||
@Value("${xxl.job.executor.logretentiondays}")
|
||||
private int logRetentionDays;
|
||||
|
||||
@Value("${xxl.job.executor.excludedpackage}")
|
||||
private String excludedPackage;
|
||||
|
||||
|
||||
@Bean
|
||||
public XxlJobSpringExecutor xxlJobExecutor() {
|
||||
logger.info(">>>>>>>>>>> xxl-job config init.");
|
||||
XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
|
||||
xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
|
||||
xxlJobSpringExecutor.setAccessToken(accessToken);
|
||||
xxlJobSpringExecutor.setTimeout(timeout);
|
||||
xxlJobSpringExecutor.setEnabled(enabled);
|
||||
xxlJobSpringExecutor.setAppname(appname);
|
||||
xxlJobSpringExecutor.setAddress(address);
|
||||
xxlJobSpringExecutor.setIp(ip);
|
||||
xxlJobSpringExecutor.setPort(port);
|
||||
xxlJobSpringExecutor.setLogPath(logPath);
|
||||
xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays);
|
||||
xxlJobSpringExecutor.setExcludedPackage(excludedPackage);
|
||||
|
||||
return xxlJobSpringExecutor;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package com.xxl.job.executor.controller;//package com.xxl.job.executor.mvc.controller;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.imfangs.dify.client.DifyClientFactory;
|
||||
import io.github.imfangs.dify.client.DifyWorkflowClient;
|
||||
import io.github.imfangs.dify.client.callback.WorkflowStreamCallback;
|
||||
import io.github.imfangs.dify.client.enums.ResponseMode;
|
||||
import io.github.imfangs.dify.client.event.*;
|
||||
import io.github.imfangs.dify.client.model.workflow.WorkflowRunRequest;
|
||||
import io.github.imfangs.dify.client.model.workflow.WorkflowRunResponse;
|
||||
import jakarta.annotation.Resource;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.ai.chat.client.ChatClient;
|
||||
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
|
||||
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
|
||||
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
|
||||
import org.springframework.ai.ollama.OllamaChatModel;
|
||||
import org.springframework.ai.ollama.api.OllamaChatOptions;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.FluxSink;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
@Controller
|
||||
@EnableAutoConfiguration
|
||||
public class IndexController {
|
||||
private static Logger logger = LoggerFactory.getLogger(IndexController.class);
|
||||
|
||||
|
||||
@RequestMapping("/")
|
||||
@ResponseBody
|
||||
String index() {
|
||||
return "xxl job ai executor running.";
|
||||
}
|
||||
|
||||
|
||||
// --------------------------------- ollama chat ---------------------------------
|
||||
|
||||
@Resource
|
||||
private OllamaChatModel ollamaChatModel;
|
||||
private String prompt = "你好,你是一个研发工程师,擅长解决技术类问题。";
|
||||
private String modle = "qwen3:0.6b";
|
||||
|
||||
/**
|
||||
* ChatClient 简单调用
|
||||
*/
|
||||
@GetMapping("/chat/simple")
|
||||
@ResponseBody
|
||||
public String simpleChat(@RequestParam(value = "input", required = false, defaultValue = "介绍你自己") String input) {
|
||||
|
||||
// build chat-client
|
||||
ChatClient ollamaChatClient = ChatClient
|
||||
.builder(ollamaChatModel)
|
||||
.defaultAdvisors(MessageChatMemoryAdvisor.builder(MessageWindowChatMemory.builder().build()).build()) // add memory
|
||||
.defaultAdvisors(SimpleLoggerAdvisor.builder().build()) // add logger
|
||||
.defaultOptions(OllamaChatOptions.builder().model(modle).build()) // assign model
|
||||
.build();
|
||||
|
||||
// call ollama
|
||||
String response = ollamaChatClient
|
||||
.prompt(prompt)
|
||||
.user(input)
|
||||
.call()
|
||||
.content();
|
||||
|
||||
logger.info("result: " + response);
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* ChatClient 流式调用
|
||||
*/
|
||||
@GetMapping("/chat/stream")
|
||||
public Flux<String> streamChat(HttpServletResponse response, @RequestParam(value = "input", required = false, defaultValue = "介绍你自己") String input) {
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
|
||||
// build chat-client
|
||||
ChatClient ollamaChatClient = ChatClient
|
||||
.builder(ollamaChatModel)
|
||||
.defaultAdvisors(MessageChatMemoryAdvisor.builder(MessageWindowChatMemory.builder().build()).build())
|
||||
.defaultAdvisors(SimpleLoggerAdvisor.builder().build())
|
||||
.defaultOptions(OllamaChatOptions.builder().model(modle).build())
|
||||
.build();
|
||||
|
||||
// call ollama
|
||||
return ollamaChatClient
|
||||
.prompt(prompt)
|
||||
.user(input)
|
||||
.stream()
|
||||
.content();
|
||||
}
|
||||
|
||||
|
||||
// --------------------------------- dify workflow ---------------------------------
|
||||
|
||||
// dify config sample
|
||||
private final String apiKey = "app-46gHBiqUb5jqAHl9TDWwnRZ8";
|
||||
private final String baseUrl = "http://localhost/v1";
|
||||
|
||||
@GetMapping("/dify/simple")
|
||||
@ResponseBody
|
||||
public String difySimple(@RequestParam(required = false, value = "input") String input) throws Exception {
|
||||
|
||||
Map<String, Object> inputs = new HashMap<>();
|
||||
inputs.put("input", input);
|
||||
|
||||
// request
|
||||
WorkflowRunRequest request = WorkflowRunRequest.builder()
|
||||
.inputs(inputs)
|
||||
.responseMode(ResponseMode.BLOCKING)
|
||||
.user("user-123")
|
||||
.build();
|
||||
|
||||
// invoke
|
||||
DifyWorkflowClient workflowClient = DifyClientFactory.createWorkflowClient(baseUrl, apiKey);
|
||||
WorkflowRunResponse response = workflowClient.runWorkflow(request);
|
||||
|
||||
// response
|
||||
return write2Json(response.getData().getOutputs());
|
||||
}
|
||||
|
||||
private String write2Json(Object obj) {
|
||||
if (obj == null) {
|
||||
return "null";
|
||||
}
|
||||
try {
|
||||
return new ObjectMapper().writeValueAsString(obj);
|
||||
} catch (JsonProcessingException e) {
|
||||
return obj.toString();
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping( "/dify/stream")
|
||||
public Flux<String> difyStream(@RequestParam(required = false, value = "input") String input) {
|
||||
|
||||
Map<String, Object> inputs = new HashMap<>();
|
||||
inputs.put("input", input);
|
||||
|
||||
// request
|
||||
WorkflowRunRequest request = WorkflowRunRequest.builder()
|
||||
.inputs(inputs)
|
||||
.responseMode(ResponseMode.STREAMING)
|
||||
.user("user-123")
|
||||
.build();
|
||||
|
||||
// invoke
|
||||
DifyWorkflowClient workflowClient = DifyClientFactory.createWorkflowClient(baseUrl, apiKey);
|
||||
return Flux.create(new Consumer<FluxSink<String>>() {
|
||||
@Override
|
||||
public void accept(FluxSink<String> sink) {
|
||||
try {
|
||||
workflowClient.runWorkflowStream(request, new WorkflowStreamCallback() {
|
||||
@Override
|
||||
public void onWorkflowStarted(WorkflowStartedEvent event) {
|
||||
sink.next("工作流开始: " + write2Json(event.getData()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNodeStarted(NodeStartedEvent event) {
|
||||
sink.next("节点开始: " + write2Json(event.getData()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNodeFinished(NodeFinishedEvent event) {
|
||||
sink.next("节点完成: " + write2Json(event.getData().getOutputs()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onWorkflowFinished(WorkflowFinishedEvent event) {
|
||||
sink.next("工作流完成: " + write2Json(event.getData().getOutputs()));
|
||||
sink.complete();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(ErrorEvent event) {
|
||||
sink.error(new RuntimeException(event.getMessage()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onException(Throwable throwable) {
|
||||
sink.error(throwable);
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
package com.xxl.job.executor.jobhandler;
|
||||
|
||||
import com.xxl.job.core.context.XxlJobHelper;
|
||||
import com.xxl.job.core.handler.annotation.XxlJob;
|
||||
import com.xxl.tool.json.GsonTool;
|
||||
import io.github.imfangs.dify.client.DifyClientFactory;
|
||||
import io.github.imfangs.dify.client.DifyWorkflowClient;
|
||||
import io.github.imfangs.dify.client.enums.ResponseMode;
|
||||
import io.github.imfangs.dify.client.model.workflow.WorkflowRunRequest;
|
||||
import io.github.imfangs.dify.client.model.workflow.WorkflowRunResponse;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.ai.chat.client.ChatClient;
|
||||
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
|
||||
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
|
||||
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
|
||||
import org.springframework.ai.ollama.OllamaChatModel;
|
||||
import org.springframework.ai.ollama.api.OllamaChatOptions;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* AI 任务开发示例
|
||||
*
|
||||
* @author xuxueli 2025-04-06
|
||||
*/
|
||||
@Component
|
||||
public class AIXxlJob {
|
||||
|
||||
// --------------------------------- ollama chat ---------------------------------
|
||||
|
||||
@Resource
|
||||
private OllamaChatModel ollamaChatModel;
|
||||
|
||||
/**
|
||||
* 1、ollama Chat任务
|
||||
*
|
||||
* 参数示例:格式见 OllamaParam
|
||||
* <pre>
|
||||
* {
|
||||
* "input": "{输入信息,必填信息}",
|
||||
* "prompt": "{模型prompt,可选信息}"
|
||||
* }
|
||||
* </pre>
|
||||
*/
|
||||
@XxlJob("ollamaJobHandler")
|
||||
public void ollamaJobHandler() {
|
||||
|
||||
// param
|
||||
String param = XxlJobHelper.getJobParam();
|
||||
if (param==null || param.trim().isEmpty()) {
|
||||
XxlJobHelper.log("param is empty.");
|
||||
|
||||
XxlJobHelper.handleFail();
|
||||
return;
|
||||
}
|
||||
|
||||
// ollama param
|
||||
OllamaParam ollamaParam = null;
|
||||
try {
|
||||
ollamaParam = GsonTool.fromJson(param, OllamaParam.class);
|
||||
if (ollamaParam.getPrompt()==null || ollamaParam.getPrompt().isBlank()) {
|
||||
ollamaParam.setPrompt("你是一个研发工程师,擅长解决技术类问题。");
|
||||
}
|
||||
if (ollamaParam.getInput() == null || ollamaParam.getInput().isBlank()) {
|
||||
XxlJobHelper.log("input is empty.");
|
||||
|
||||
XxlJobHelper.handleFail();
|
||||
return;
|
||||
}
|
||||
if (ollamaParam.getModel()==null || ollamaParam.getModel().isBlank()) {
|
||||
ollamaParam.setModel("qwen3:0.6b");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
XxlJobHelper.log(new RuntimeException("OllamaParam parse error", e));
|
||||
XxlJobHelper.handleFail();
|
||||
return;
|
||||
}
|
||||
|
||||
// input
|
||||
XxlJobHelper.log("<br><br><b>【Input】: " + ollamaParam.getInput()+ "</b><br><br>");
|
||||
|
||||
// build chat-client
|
||||
ChatClient ollamaChatClient = ChatClient
|
||||
.builder(ollamaChatModel)
|
||||
.defaultAdvisors(MessageChatMemoryAdvisor.builder(MessageWindowChatMemory.builder().build()).build())
|
||||
.defaultAdvisors(SimpleLoggerAdvisor.builder().build())
|
||||
.defaultOptions(OllamaChatOptions.builder().model(ollamaParam.getModel()).build())
|
||||
.build();
|
||||
|
||||
// call ollama
|
||||
String response = ollamaChatClient
|
||||
.prompt(ollamaParam.getPrompt())
|
||||
.user(ollamaParam.getInput())
|
||||
.call()
|
||||
.content();
|
||||
|
||||
XxlJobHelper.log("<br><br><b>【Output】: " + response + "</b><br><br>");
|
||||
}
|
||||
|
||||
private static class OllamaParam{
|
||||
private String input;
|
||||
private String prompt;
|
||||
private String model;
|
||||
|
||||
public String getInput() {
|
||||
return input;
|
||||
}
|
||||
|
||||
public void setInput(String input) {
|
||||
this.input = input;
|
||||
}
|
||||
|
||||
public String getPrompt() {
|
||||
return prompt;
|
||||
}
|
||||
|
||||
public void setPrompt(String prompt) {
|
||||
this.prompt = prompt;
|
||||
}
|
||||
|
||||
public String getModel() {
|
||||
return model;
|
||||
}
|
||||
|
||||
public void setModel(String model) {
|
||||
this.model = model;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// --------------------------------- dify workflow ---------------------------------
|
||||
|
||||
/**
|
||||
* 2、dify Workflow任务
|
||||
*
|
||||
* 参数示例:格式见 DifyParam
|
||||
* <pre>
|
||||
* {
|
||||
* "inputs":{ // inputs 为dify工作流任务参数;参数不固定,结合各自 workflow 自行定义。
|
||||
* "input":"{用户输入信息}" // 该参数为示例变量,需要 workflow 的“开始”节点 自定义参数 “input”,可自行调整或删除。
|
||||
* },
|
||||
* "user": "{用户标识,选填}"
|
||||
* }
|
||||
* </pre>
|
||||
*/
|
||||
@XxlJob("difyWorkflowJobHandler")
|
||||
public void difyWorkflowJobHandler() throws Exception {
|
||||
|
||||
// param
|
||||
String param = XxlJobHelper.getJobParam();
|
||||
if (param==null || param.trim().isEmpty()) {
|
||||
XxlJobHelper.log("param is empty.");
|
||||
XxlJobHelper.handleFail();
|
||||
return;
|
||||
}
|
||||
|
||||
// param parse
|
||||
DifyParam difyParam;
|
||||
try {
|
||||
difyParam =GsonTool.fromJson(param, DifyParam.class);
|
||||
if (difyParam.getInputs() == null) {
|
||||
difyParam.setInputs(new HashMap<>());
|
||||
}
|
||||
if (difyParam.getUser() == null) {
|
||||
difyParam.setUser("xxl-job");
|
||||
}
|
||||
if (difyParam.getBaseUrl()==null || difyParam.getApiKey()==null) {
|
||||
XxlJobHelper.log("baseUrl or apiKey invalid.");
|
||||
XxlJobHelper.handleFail();
|
||||
return;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
XxlJobHelper.log(new RuntimeException("DifyParam parse error", e));
|
||||
XxlJobHelper.handleFail();
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// dify param
|
||||
XxlJobHelper.log("<br><br><b>【inputs】: " + difyParam.getInputs() + "</b><br><br>");
|
||||
|
||||
// dify request
|
||||
WorkflowRunRequest request = WorkflowRunRequest.builder()
|
||||
.inputs(difyParam.getInputs())
|
||||
.responseMode(ResponseMode.BLOCKING)
|
||||
.user(difyParam.getUser())
|
||||
.build();
|
||||
|
||||
// dify invoke
|
||||
DifyWorkflowClient workflowClient = DifyClientFactory.createWorkflowClient(difyParam.getBaseUrl(), difyParam.getApiKey());
|
||||
WorkflowRunResponse response = workflowClient.runWorkflow(request);
|
||||
|
||||
// response
|
||||
XxlJobHelper.log("<br><br><b>【Output】: " + response.getData().getOutputs()+ "</b><br><br>");
|
||||
}
|
||||
|
||||
private static class DifyParam{
|
||||
|
||||
/**
|
||||
* dify input, 允许传入 Dify App 定义的各变量值
|
||||
*/
|
||||
private Map<String, Object> inputs;
|
||||
|
||||
/**
|
||||
* dify user
|
||||
*/
|
||||
private String user;
|
||||
|
||||
/**
|
||||
* dify baseUrl
|
||||
*/
|
||||
private String baseUrl;
|
||||
|
||||
/**
|
||||
* dify apiKey
|
||||
*/
|
||||
private String apiKey;
|
||||
|
||||
public Map<String, Object> getInputs() {
|
||||
return inputs;
|
||||
}
|
||||
|
||||
public void setInputs(Map<String, Object> inputs) {
|
||||
this.inputs = inputs;
|
||||
}
|
||||
|
||||
public String getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(String user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public String getBaseUrl() {
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
public void setBaseUrl(String baseUrl) {
|
||||
this.baseUrl = baseUrl;
|
||||
}
|
||||
|
||||
public String getApiKey() {
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
public void setApiKey(String apiKey) {
|
||||
this.apiKey = apiKey;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
# web port
|
||||
server.port=8082
|
||||
# no web
|
||||
#spring.main.web-environment=false
|
||||
|
||||
server.servlet.encoding.force=true
|
||||
server.servlet.encoding.charset=UTF-8
|
||||
|
||||
# log config
|
||||
logging.config=classpath:logback.xml
|
||||
|
||||
|
||||
### xxl-job admin address list, such as "http://address" or "http://address01,http://address02"
|
||||
xxl.job.admin.addresses=http://127.0.0.1:8080/xxl-job-admin
|
||||
### xxl-job access token
|
||||
xxl.job.admin.accessToken=default_token
|
||||
### xxl-job timeout by second, default 3s
|
||||
xxl.job.admin.timeout=3
|
||||
|
||||
### xxl-job executor enable, default true
|
||||
xxl.job.executor.enabled=true
|
||||
### xxl-job executor appname
|
||||
xxl.job.executor.appname=xxl-job-executor-sample-ai
|
||||
### xxl-job executor registry-address: default use address to registry , otherwise use ip:port if address is null
|
||||
xxl.job.executor.address=
|
||||
### xxl-job executor server-info
|
||||
xxl.job.executor.ip=
|
||||
xxl.job.executor.port=9997
|
||||
### xxl-job executor log-path
|
||||
xxl.job.executor.logpath=/data/applogs/xxl-job/jobhandler
|
||||
### xxl-job executor log-retention-days
|
||||
xxl.job.executor.logretentiondays=30
|
||||
### xxl-job executor excluded package, will skip scan job. such as "org.package01" or "org.package01,org.package02"
|
||||
xxl.job.executor.excludedpackage=
|
||||
|
||||
|
||||
### ollama
|
||||
spring.ai.model.chat=ollama
|
||||
### ollama url
|
||||
spring.ai.ollama.base-url=http://localhost:11434
|
||||
@@ -0,0 +1,27 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration debug="false" scan="true" scanPeriod="1 seconds">
|
||||
|
||||
<contextName>logback</contextName>
|
||||
<property name="log.path" value="${LOG_HOME:-/data/applogs}/xxl-job/xxl-job-executor-sample-springboot-ai.log" />
|
||||
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${log.path}</file>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<fileNamePattern>${log.path}.%d{yyyy-MM-dd}.log</fileNamePattern>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="info">
|
||||
<appender-ref ref="console"/>
|
||||
<!--<appender-ref ref="file"/>-->
|
||||
</root>
|
||||
|
||||
</configuration>
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.xxl.job.executor.test;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
public class BaseTests {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
System.out.println(11);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.xxl.job.executor.test.dify;
|
||||
|
||||
import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
|
||||
import io.github.imfangs.dify.client.DifyClientFactory;
|
||||
import io.github.imfangs.dify.client.DifyWorkflowClient;
|
||||
import io.github.imfangs.dify.client.enums.ResponseMode;
|
||||
import io.github.imfangs.dify.client.model.workflow.WorkflowRunRequest;
|
||||
import io.github.imfangs.dify.client.model.workflow.WorkflowRunResponse;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@SpringBootTest
|
||||
public class DifyTest {
|
||||
private static final Logger logger = LoggerFactory.getLogger(DifyTest.class);
|
||||
|
||||
// ignore
|
||||
@MockitoBean
|
||||
private XxlJobSpringExecutor xxlJobSpringExecutor;
|
||||
|
||||
@Test
|
||||
public void test() throws Exception {
|
||||
|
||||
String baseUrl = "https://xx.ai";
|
||||
String apiKey = "xx";
|
||||
String user = "zhangsan";
|
||||
Map<String, Object> inputs = Map.of(
|
||||
"input", "请写一个java程序,实现一个方法,输入一个字符串,返回字符串的长度。"
|
||||
);
|
||||
|
||||
// dify request
|
||||
WorkflowRunRequest request = WorkflowRunRequest.builder()
|
||||
.inputs(inputs)
|
||||
.responseMode(ResponseMode.BLOCKING)
|
||||
.user(user)
|
||||
.build();
|
||||
|
||||
// dify invoke
|
||||
DifyWorkflowClient workflowClient = DifyClientFactory.createWorkflowClient(baseUrl, apiKey);
|
||||
WorkflowRunResponse response = workflowClient.runWorkflow(request);
|
||||
|
||||
// response
|
||||
logger.info("input: " + inputs);
|
||||
logger.info("output: " + response.getData().getOutputs());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.xxl.job.executor.test.ollama;
|
||||
|
||||
import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.ai.chat.client.ChatClient;
|
||||
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
|
||||
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
|
||||
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
|
||||
import org.springframework.ai.ollama.OllamaChatModel;
|
||||
import org.springframework.ai.ollama.api.OllamaChatOptions;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@SpringBootTest
|
||||
public class OllamaTest {
|
||||
private static final Logger logger = LoggerFactory.getLogger(OllamaTest.class);
|
||||
|
||||
// ignore
|
||||
@MockitoBean
|
||||
private XxlJobSpringExecutor xxlJobSpringExecutor;
|
||||
|
||||
|
||||
@Resource
|
||||
private OllamaChatModel ollamaChatModel;
|
||||
|
||||
@Test
|
||||
public void chatTest() {
|
||||
|
||||
String model = "qwen3:0.6b";
|
||||
String prompt = "背景说明:你是一个研发工程师,擅长解决技术类问题。";
|
||||
String input = "请写一个java程序,实现一个方法,输入一个字符串,返回字符串的长度。";
|
||||
|
||||
|
||||
// build chat-client
|
||||
ChatClient ollamaChatClient = ChatClient
|
||||
.builder(ollamaChatModel)
|
||||
.defaultAdvisors(MessageChatMemoryAdvisor.builder(MessageWindowChatMemory.builder().build()).build())
|
||||
.defaultAdvisors(SimpleLoggerAdvisor.builder().build())
|
||||
.defaultOptions(OllamaChatOptions.builder().model(model).build())
|
||||
.build();
|
||||
|
||||
// call ollama
|
||||
String response = ollamaChatClient
|
||||
.prompt(prompt)
|
||||
.user(input)
|
||||
.call()
|
||||
.content();
|
||||
|
||||
logger.info("input: {}", input);
|
||||
logger.info("response: {}", response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void chatStreamTest() throws InterruptedException {
|
||||
|
||||
String model = "qwen3:0.6b";
|
||||
String prompt = "背景说明:你是一个研发工程师,擅长解决技术类问题。";
|
||||
String input = "请写一个java程序,实现一个方法,输入一个字符串,返回字符串的长度。";
|
||||
|
||||
|
||||
// build chat-client
|
||||
ChatClient ollamaChatClient = ChatClient
|
||||
.builder(ollamaChatModel)
|
||||
.defaultAdvisors(MessageChatMemoryAdvisor.builder(MessageWindowChatMemory.builder().build()).build())
|
||||
.defaultAdvisors(SimpleLoggerAdvisor.builder().build())
|
||||
.defaultOptions(OllamaChatOptions.builder().model(model).build())
|
||||
.build();
|
||||
|
||||
// call ollama
|
||||
logger.info("input: {}", input);
|
||||
Flux<String> flux = ollamaChatClient
|
||||
.prompt(prompt)
|
||||
.user(input)
|
||||
.stream()
|
||||
.content();
|
||||
|
||||
flux.subscribe(
|
||||
data -> System.out.println("Received: " + data), // onNext 处理
|
||||
error -> System.err.println("Error: " + error), // onError 处理
|
||||
() -> System.out.println("Completed") // onComplete 处理
|
||||
);
|
||||
|
||||
TimeUnit.SECONDS.sleep(10);
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
# base image
|
||||
FROM openjdk:21-jdk-slim
|
||||
|
||||
# maintainer
|
||||
MAINTAINER xuxueli
|
||||
|
||||
# set params
|
||||
ENV PARAMS=""
|
||||
|
||||
# set timezone
|
||||
ENV TZ=PRC
|
||||
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
|
||||
|
||||
# copy jar
|
||||
ADD target/xxl-job-executor-sample-springboot-*.jar /app.jar
|
||||
|
||||
# command
|
||||
# log home: -e LOG_HOME=/data/applogs
|
||||
# jvm options: -e JAVA_OPTS="-Xms128m -Xmx128m"
|
||||
# app params: -e PARAMS="--server.port=8080"
|
||||
ENTRYPOINT ["sh","-c","java ${LOG_HOME:+-DLOG_HOME=$LOG_HOME} -jar $JAVA_OPTS /app.jar $PARAMS"]
|
||||
@@ -0,0 +1,59 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.xuxueli</groupId>
|
||||
<artifactId>xxl-job-executor-samples</artifactId>
|
||||
<version>3.3.2</version>
|
||||
</parent>
|
||||
<artifactId>xxl-job-executor-sample-springboot</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>${project.artifactId}</name>
|
||||
<description>Example executor project for spring boot.</description>
|
||||
<url>https://www.xuxueli.com/</url>
|
||||
|
||||
<properties>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- spring-boot-starter-web (spring-webmvc + tomcat) -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- xxl-job-core -->
|
||||
<dependency>
|
||||
<groupId>com.xuxueli</groupId>
|
||||
<artifactId>xxl-job-core</artifactId>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.xxl.job.executor;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
/**
|
||||
* @author xuxueli 2018-10-28 00:38:13
|
||||
*/
|
||||
@SpringBootApplication
|
||||
public class XxlJobExecutorApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(XxlJobExecutorApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.xxl.job.executor.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;
|
||||
|
||||
/**
|
||||
* xxl-job config
|
||||
*
|
||||
* @author xuxueli 2017-04-28
|
||||
*/
|
||||
@Configuration
|
||||
public class XxlJobConfig {
|
||||
private static final Logger logger = LoggerFactory.getLogger(XxlJobConfig.class);
|
||||
|
||||
@Value("${xxl.job.admin.addresses}")
|
||||
private String adminAddresses;
|
||||
|
||||
@Value("${xxl.job.admin.accessToken}")
|
||||
private String accessToken;
|
||||
|
||||
@Value("${xxl.job.admin.timeout}")
|
||||
private int timeout;
|
||||
|
||||
@Value("${xxl.job.executor.enabled}")
|
||||
private Boolean enabled;
|
||||
|
||||
@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.executor.logpath}")
|
||||
private String logPath;
|
||||
|
||||
@Value("${xxl.job.executor.logretentiondays}")
|
||||
private int logRetentionDays;
|
||||
|
||||
@Value("${xxl.job.executor.excludedpackage}")
|
||||
private String excludedPackage;
|
||||
|
||||
|
||||
@Bean
|
||||
public XxlJobSpringExecutor xxlJobExecutor() {
|
||||
logger.info(">>>>>>>>>>> xxl-job config init.");
|
||||
XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
|
||||
xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
|
||||
xxlJobSpringExecutor.setAccessToken(accessToken);
|
||||
xxlJobSpringExecutor.setTimeout(timeout);
|
||||
xxlJobSpringExecutor.setEnabled(enabled);
|
||||
xxlJobSpringExecutor.setAppname(appname);
|
||||
xxlJobSpringExecutor.setAddress(address);
|
||||
xxlJobSpringExecutor.setIp(ip);
|
||||
xxlJobSpringExecutor.setPort(port);
|
||||
xxlJobSpringExecutor.setLogPath(logPath);
|
||||
xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays);
|
||||
xxlJobSpringExecutor.setExcludedPackage(excludedPackage);
|
||||
|
||||
return xxlJobSpringExecutor;
|
||||
}
|
||||
|
||||
/**
|
||||
* 针对多网卡、容器内部署等情况,可借助 "spring-cloud-commons" 提供的 "InetUtils" 组件灵活定制注册IP;
|
||||
*
|
||||
* 1、引入依赖:
|
||||
* <dependency>
|
||||
* <groupId>org.springframework.cloud</groupId>
|
||||
* <artifactId>spring-cloud-commons</artifactId>
|
||||
* <version>${version}</version>
|
||||
* </dependency>
|
||||
*
|
||||
* 2、配置文件,或者容器启动变量
|
||||
* spring.cloud.inetutils.preferred-networks: 'xxx.xxx.xxx.'
|
||||
*
|
||||
* 3、获取IP
|
||||
* String ip_ = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
|
||||
*/
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
//package com.xxl.job.executor.mvc.controller;
|
||||
//
|
||||
//import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
//import org.springframework.stereotype.Controller;
|
||||
//import org.springframework.web.bind.annotation.RequestMapping;
|
||||
//import org.springframework.web.bind.annotation.ResponseBody;
|
||||
//
|
||||
//@Controller
|
||||
//@EnableAutoConfiguration
|
||||
//public class IndexController {
|
||||
//
|
||||
// @RequestMapping("/")
|
||||
// @ResponseBody
|
||||
// String index() {
|
||||
// return "xxl job executor running.";
|
||||
// }
|
||||
//
|
||||
//}
|
||||
@@ -0,0 +1,389 @@
|
||||
package com.xxl.job.executor.jobhandler;
|
||||
|
||||
import com.xxl.job.core.context.XxlJobHelper;
|
||||
import com.xxl.job.core.handler.annotation.XxlJob;
|
||||
import com.xxl.tool.core.StringTool;
|
||||
import com.xxl.tool.json.GsonTool;
|
||||
import com.xxl.tool.http.HttpTool;
|
||||
import com.xxl.tool.http.http.HttpResponse;
|
||||
import com.xxl.tool.http.http.enums.ContentType;
|
||||
import com.xxl.tool.http.http.enums.Method;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* XxlJob开发示例(Bean模式)
|
||||
*
|
||||
* 开发步骤:
|
||||
* 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
|
||||
*/
|
||||
@Component
|
||||
public class SampleXxlJob {
|
||||
private static final Logger logger = LoggerFactory.getLogger(SampleXxlJob.class);
|
||||
|
||||
|
||||
/**
|
||||
* 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);
|
||||
TimeUnit.SECONDS.sleep(2);
|
||||
}
|
||||
// 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、命令行任务
|
||||
*
|
||||
* 参数示例:"ls -a" 或者 "pwd"
|
||||
*/
|
||||
@XxlJob("commandJobHandler")
|
||||
public void commandJobHandler() throws Exception {
|
||||
String command = XxlJobHelper.getJobParam();
|
||||
int exitValue = -1;
|
||||
|
||||
BufferedReader bufferedReader = null;
|
||||
try {
|
||||
// valid
|
||||
if (command==null || command.trim().length()==0) {
|
||||
XxlJobHelper.handleFail("command empty.");
|
||||
return;
|
||||
}
|
||||
|
||||
// command split
|
||||
String[] commandArray = command.split(" ");
|
||||
|
||||
// command process
|
||||
ProcessBuilder processBuilder = new ProcessBuilder();
|
||||
processBuilder.command(commandArray);
|
||||
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任务
|
||||
*
|
||||
* 参数示例:
|
||||
* <pre>
|
||||
* // 1、简单示例:
|
||||
* {
|
||||
* "url": "http://www.baidu.com",
|
||||
* "method": "get",
|
||||
* "data": "hello world"
|
||||
* }
|
||||
*
|
||||
* // 2、完整参数示例:
|
||||
* {
|
||||
* "url": "http://www.baidu.com",
|
||||
* "method": "POST",
|
||||
* "contentType": "application/json",
|
||||
* "headers": {
|
||||
* "header01": "value01"
|
||||
* },
|
||||
* "cookies": {
|
||||
* "cookie01": "value01"
|
||||
* },
|
||||
* "timeout": 3000,
|
||||
* "data": "request body data",
|
||||
* "form": {
|
||||
* "key01": "value01"
|
||||
* },
|
||||
* "auth": "auth data"
|
||||
* }
|
||||
* </pre>
|
||||
*/
|
||||
@XxlJob("httpJobHandler")
|
||||
public void httpJobHandler() throws Exception {
|
||||
|
||||
// param data
|
||||
String param = XxlJobHelper.getJobParam();
|
||||
if (param==null || param.trim().isEmpty()) {
|
||||
XxlJobHelper.log("param["+ param +"] invalid.");
|
||||
|
||||
XxlJobHelper.handleFail();
|
||||
return;
|
||||
}
|
||||
|
||||
// param parse
|
||||
HttpJobParam httpJobParam = null;
|
||||
try {
|
||||
httpJobParam = GsonTool.fromJson(param, HttpJobParam.class);
|
||||
} catch (Exception e) {
|
||||
XxlJobHelper.log(new RuntimeException("HttpJobParam parse error", e));
|
||||
XxlJobHelper.handleFail();
|
||||
return;
|
||||
}
|
||||
|
||||
// param valid
|
||||
if (httpJobParam == null) {
|
||||
XxlJobHelper.log("param parse fail.");
|
||||
XxlJobHelper.handleFail();
|
||||
return;
|
||||
}
|
||||
if (StringTool.isBlank(httpJobParam.getUrl())) {
|
||||
XxlJobHelper.log("url["+ httpJobParam.getUrl() +"] invalid.");
|
||||
XxlJobHelper.handleFail();
|
||||
return;
|
||||
}
|
||||
if (!isValidDomain(httpJobParam.getUrl())) {
|
||||
XxlJobHelper.log("url["+ httpJobParam.getUrl() +"] not allowed.");
|
||||
XxlJobHelper.handleFail();
|
||||
return;
|
||||
}
|
||||
Method method = Method.POST;
|
||||
if (StringTool.isNotBlank(httpJobParam.getMethod())) {
|
||||
Method methodParam = Method.valueOf(httpJobParam.getMethod().toUpperCase());
|
||||
if (methodParam == null) {
|
||||
XxlJobHelper.log("method["+ httpJobParam.getMethod() +"] invalid.");
|
||||
XxlJobHelper.handleFail();
|
||||
return;
|
||||
}
|
||||
method = methodParam;
|
||||
}
|
||||
ContentType contentType = ContentType.JSON;
|
||||
if (StringTool.isNotBlank(httpJobParam.getContentType())) {
|
||||
for (ContentType contentTypeParam : ContentType.values()) {
|
||||
if (contentTypeParam.getValue().equals(httpJobParam.getContentType())) {
|
||||
contentType = contentTypeParam;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (httpJobParam.getTimeout() <= 0) {
|
||||
httpJobParam.setTimeout(3000);
|
||||
}
|
||||
|
||||
// do request
|
||||
try {
|
||||
HttpResponse httpResponse = HttpTool.createRequest()
|
||||
.url(httpJobParam.getUrl())
|
||||
.method(method)
|
||||
.contentType(contentType)
|
||||
.header(httpJobParam.getHeaders())
|
||||
.cookie(httpJobParam.getCookies())
|
||||
.body(httpJobParam.getData())
|
||||
.form(httpJobParam.getForm())
|
||||
.auth(httpJobParam.getAuth())
|
||||
.execute();
|
||||
|
||||
XxlJobHelper.log("StatusCode: " + httpResponse.statusCode());
|
||||
XxlJobHelper.log("Response: <br>" + httpResponse.response());
|
||||
} catch (Exception e) {
|
||||
XxlJobHelper.log(e);
|
||||
XxlJobHelper.handleFail();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* domain white-list, for httpJobHandler
|
||||
*/
|
||||
private static Set<String> DOMAIN_WHITE_LIST = Set.of(
|
||||
"http://www.baidu.com",
|
||||
"http://cn.bing.com"
|
||||
);
|
||||
|
||||
/**
|
||||
* valid if domain is in white-list
|
||||
*/
|
||||
private boolean isValidDomain(String url) {
|
||||
if (url == null || DOMAIN_WHITE_LIST.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
for (String prefix : DOMAIN_WHITE_LIST) {
|
||||
if (url.startsWith(prefix)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/*public static void main(String[] args) {
|
||||
HttpJobParam httpJobParam = new HttpJobParam();
|
||||
httpJobParam.setUrl("http://www.baidu.com");
|
||||
httpJobParam.setMethod(Method.POST.name());
|
||||
httpJobParam.setContentType(ContentType.JSON.getValue());
|
||||
httpJobParam.setHeaders(Map.of("header01", "value01"));
|
||||
httpJobParam.setCookies(Map.of("cookie01", "value01"));
|
||||
httpJobParam.setTimeout(3000);
|
||||
httpJobParam.setData("request body data");
|
||||
httpJobParam.setForm(Map.of("form01", "value01"));
|
||||
httpJobParam.setAuth("auth data");
|
||||
|
||||
logger.info(GsonTool.toJson(httpJobParam));
|
||||
}*/
|
||||
|
||||
/**
|
||||
* http job param
|
||||
*/
|
||||
private static class HttpJobParam{
|
||||
private String url; // 请求 Url
|
||||
private String method; // Method
|
||||
private String contentType; // Content-Type
|
||||
private Map<String, String> headers; // 存储请求头
|
||||
private Map<String, String> cookies; // Cookie(需要格式转换)
|
||||
private int timeout; // 请求超时时间
|
||||
private String data; // 存储请求体
|
||||
private Map<String, String> form; // 存储表单数据
|
||||
private String auth; // 鉴权信息
|
||||
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
public void setUrl(String url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
public String getMethod() {
|
||||
return method;
|
||||
}
|
||||
|
||||
public void setMethod(String method) {
|
||||
this.method = method;
|
||||
}
|
||||
|
||||
public String getContentType() {
|
||||
return contentType;
|
||||
}
|
||||
|
||||
public void setContentType(String contentType) {
|
||||
this.contentType = contentType;
|
||||
}
|
||||
|
||||
public Map<String, String> getHeaders() {
|
||||
return headers;
|
||||
}
|
||||
|
||||
public void setHeaders(Map<String, String> headers) {
|
||||
this.headers = headers;
|
||||
}
|
||||
|
||||
public Map<String, String> getCookies() {
|
||||
return cookies;
|
||||
}
|
||||
|
||||
public void setCookies(Map<String, String> cookies) {
|
||||
this.cookies = cookies;
|
||||
}
|
||||
|
||||
public int getTimeout() {
|
||||
return timeout;
|
||||
}
|
||||
|
||||
public void setTimeout(int timeout) {
|
||||
this.timeout = timeout;
|
||||
}
|
||||
|
||||
public String getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public void setData(String data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public Map<String, String> getForm() {
|
||||
return form;
|
||||
}
|
||||
|
||||
public void setForm(Map<String, String> form) {
|
||||
this.form = form;
|
||||
}
|
||||
|
||||
public String getAuth() {
|
||||
return auth;
|
||||
}
|
||||
|
||||
public void setAuth(String auth) {
|
||||
this.auth = auth;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 5、生命周期任务示例:任务初始化与销毁时,支持自定义相关逻辑;
|
||||
*/
|
||||
@XxlJob(value = "demoJobHandler2", init = "init", destroy = "destroy")
|
||||
public void demoJobHandler2() throws Exception {
|
||||
XxlJobHelper.log("XXL-JOB, Hello World.");
|
||||
}
|
||||
public void init(){
|
||||
logger.info("init");
|
||||
}
|
||||
public void destroy(){
|
||||
logger.info("destroy");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
# web port
|
||||
server.port=8081
|
||||
# no web
|
||||
#spring.main.web-environment=false
|
||||
|
||||
# log config
|
||||
logging.config=classpath:logback.xml
|
||||
|
||||
|
||||
### xxl-job admin address list, such as "http://address" or "http://address01,http://address02"
|
||||
xxl.job.admin.addresses=http://127.0.0.1:8080/xxl-job-admin
|
||||
### xxl-job access token
|
||||
xxl.job.admin.accessToken=default_token
|
||||
### xxl-job timeout by second, default 3s
|
||||
xxl.job.admin.timeout=3
|
||||
|
||||
### xxl-job executor enable, default true
|
||||
xxl.job.executor.enabled=true
|
||||
### xxl-job executor appname
|
||||
xxl.job.executor.appname=xxl-job-executor-sample
|
||||
### xxl-job executor registry-address: default use address to registry , otherwise use ip:port if address is null
|
||||
xxl.job.executor.address=
|
||||
### xxl-job executor server-info
|
||||
xxl.job.executor.ip=
|
||||
xxl.job.executor.port=9999
|
||||
### xxl-job executor log-path
|
||||
xxl.job.executor.logpath=/data/applogs/xxl-job/jobhandler
|
||||
### xxl-job executor log-retention-days
|
||||
xxl.job.executor.logretentiondays=30
|
||||
### xxl-job executor excluded package, will skip scan job. such as "org.package01" or "org.package01,org.package02"
|
||||
xxl.job.executor.excludedpackage=
|
||||
@@ -0,0 +1,27 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration debug="false" scan="true" scanPeriod="1 seconds">
|
||||
|
||||
<contextName>logback</contextName>
|
||||
<property name="log.path" value="${LOG_HOME:-/data/applogs}/xxl-job/xxl-job-executor-sample-springboot.log" />
|
||||
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${log.path}</file>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<fileNamePattern>${log.path}.%d{yyyy-MM-dd}.log</fileNamePattern>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="info">
|
||||
<appender-ref ref="console"/>
|
||||
<!--<appender-ref ref="file"/>-->
|
||||
</root>
|
||||
|
||||
</configuration>
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.xxl.job.executor.test;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
public class XxlJobExecutorExampleBootApplicationTests {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
System.out.println(11);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user