Commit e34c15b0 by tiger

job

1 parent d9cf876e
......@@ -9,3 +9,5 @@
*.container
*.name
/platform-process-api/*.factorypath
/platform-process/*.path_IS_UNDEFINED
/platform-process/*.gz
......@@ -22,6 +22,16 @@
<groupId>com.glsx</groupId>
<artifactId>rest-admin-feign</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>32.1.2-jre</version>
</dependency>
</dependencies>
</project>
package cn.com.glsx.process.modules.entity;
import javax.persistence.*;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name = "sop_inst_node")
public class SopInstNode {
......
package cn.com.glsx.process.modules.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.Sets;
import cn.com.glsx.process.modules.entity.SopInst;
import cn.com.glsx.process.modules.entity.SopInstBatch;
import cn.com.glsx.process.modules.entity.SopInstNode;
......@@ -38,4 +42,39 @@ public class SopStruct {
/** 实例当前批次 */
private SopInstBatch batch;
/** 所有节点执行顺序 */
public List<Integer> getNodeSort() {
List<Integer> sort = new ArrayList<>();
Set<Integer> keys = Sets.newHashSet();
int i = 0;
while (keys.size() < instLinkMap.keySet().size()) {
Set<Integer> sets = instLinkMap.keySet();
for (Integer key : sets) {
i++;
Pair<Set<Integer>, Set<Integer>> pair = instLinkMap.get(key);
if (!keys.contains(key)) {
// 第一个节点:直接执行
if (pair.getKey().isEmpty()) {
keys.add(key);
sort.add(key);
continue;
}
// 非第一个节点:判断前置节点
if (keys.containsAll(pair.getKey())) {
keys.add(key);
sort.add(key);
continue;
}
} else {
// 进入后置节点
sets = pair.getValue();
continue;
}
}
if (i++ > 1000) {
throw new RuntimeException("Sop实例:【" + inst.getInstId() + "-" + inst.getInstName() + "】节点不闭环,请检查!");
}
}
return sort;
}
}
......@@ -58,6 +58,13 @@ public class DynamicTaskService {
log.info("【动态任务】{},创建:cron:{}, job:{}", jobName, cron, instance.getClass().getSimpleName());
}
public void create(String jobName, String cron, SimpleJob instance, String description, String param, boolean enabled) {
LiteJobConfiguration jobConfig = simpleJobConfigBuilder(jobName, instance.getClass(), 1, cron, description, param).overwrite(true)
.disabled(!enabled).build();
new SpringJobScheduler(instance, zookeeperRegistryCenter, jobConfig, elasticJobListener).init();
log.info("【动态任务】{},创建:cron:{},job:{},enabled:{}", jobName, cron, instance.getClass().getSimpleName(), enabled);
}
/**
* 更新定时任务
*
......
package cn.com.glsx.process.job.instance;
import java.util.Date;
import java.util.Set;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
......@@ -11,7 +12,9 @@ import cn.com.glsx.process.modules.entity.SopInstNode;
import cn.com.glsx.process.modules.model.SopStruct;
import cn.com.glsx.process.modules.service.SopService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
/**
......@@ -40,14 +43,25 @@ public class SopInstExecuteJob implements SimpleJob {
// TODO 创建所有节点任务
for (SopInstNode node : sop.getInstNodeMap().values()) {
// 前置节点,后置节点
Pair<Set<Integer>, Set<Integer>> linkPair = sop.getInstLinkMap().get(node.getNodeId());
boolean enabled = linkPair == null || linkPair.getKey().isEmpty();
SopInstNodeParam param = new SopInstNodeParam();
param.setInstNodeId(node.getInstNodeId());
param.setPreIds(linkPair.getKey());
String paramJson = JSONUtil.toJsonStr(param);
if (StrUtil.isNotBlank(node.getNodeCron())) {
taskService.create(SopInstLoadJob.jobName(sop.getInst(), node), node.getNodeCron(), 1, new SopInstNodeJob(),
sop.getInst().getInstName() + "-" + node.getNodeName(), node.getInstNodeId() + "");
// 按cron表达式执行
taskService.create(SopInstLoadJob.jobName(sop.getInst(), node), node.getNodeCron(), new SopInstNodeJob(),
sop.getInst().getInstName() + "-" + node.getNodeName(), paramJson, enabled);
} else {
// 1分钟后执行: 11 12 8 2 3 ? 2024
//
// 立即执行: 1分钟后执行: 11 12 8 2 3 ? 2024
String cron = DateUtil.format(org.apache.commons.lang.time.DateUtils.addMinutes(new Date(), 1), "s m H d M ? yyyy");
taskService.create(SopInstLoadJob.jobName(sop.getInst(), node), cron, 1, new SopInstNodeJob(),
sop.getInst().getInstName() + "-" + node.getNodeName(), node.getInstNodeId() + "");
taskService.create(SopInstLoadJob.jobName(sop.getInst(), node), cron, new SopInstNodeJob(),
sop.getInst().getInstName() + "-" + node.getNodeName(), paramJson, enabled);
}
}
......
package cn.com.glsx.process.job.instance;
import java.util.Date;
import java.util.Set;
import com.dangdang.ddframe.job.api.ShardingContext;
......@@ -7,8 +8,13 @@ import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.glsx.plat.context.utils.SpringUtils;
import cn.com.glsx.process.job.DynamicTaskService;
import cn.com.glsx.process.modules.entity.SopInstNode;
import cn.com.glsx.process.modules.model.SopStruct;
import cn.com.glsx.process.modules.service.SopService;
import lombok.Data;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
/**
......@@ -23,22 +29,51 @@ public class SopInstNodeJob implements SimpleJob {
@Override
public void execute(ShardingContext shardingContext) {
// 参数
String instNodeId = shardingContext.getJobParameter();
log.info("---------SopInstNodeJob------------- instNodeId:{}", instNodeId);
String json = shardingContext.getJobParameter();
SopInstNodeParam param = JSONUtil.toBean(json, SopInstNodeParam.class);
log.info("---------SopInstNodeJob------------- param:{}", json);
SopService sopService = SpringUtils.getBean(SopService.class);
DynamicTaskService taskService = SpringUtils.getBean(DynamicTaskService.class);
SopStruct sop = sopService.loadSopByInstNodeId(param.getInstNodeId());
if (taskService.isJobStoped(SopInstLoadJob.jobName(sop.getInst()))) {
// TODO 停止sop所有子任务
return;
}
// trigger next node???
SopInstNode node = sop.getInstNodeMap().get(param.getInstNodeId());
handleNode(node);
triggerNext(sop, node, param);
}
public void triggerNext(SopStruct sop, SopInstNode node, SopInstNodeParam param) {
// 前置节点,后置节点
Pair<Set<Integer>, Set<Integer>> linkPair = sop.getInstLinkMap().get(node.getNodeId());
// TODO 加载后置节点对应的任务列表
boolean enabled = linkPair == null || linkPair.getKey().isEmpty();
param.setInstNodeId(node.getInstNodeId());
param.setPreIds(linkPair.getKey());
String paramJson = JSONUtil.toJsonStr(param);
@Data
public static class SopInstNodeParam {
/** 实例节点id */
private String instNodeId;
String cron = DateUtil.format(org.apache.commons.lang.time.DateUtils.addMinutes(new Date(), 1), "s m H d M ? yyyy");
cron = StrUtil.isBlank(node.getNodeCron()) ? cron : node.getNodeCron();
DynamicTaskService taskService = SpringUtils.getBean(DynamicTaskService.class);
// 按cron表达式执行
taskService.create(SopInstLoadJob.jobName(sop.getInst(), node), node.getNodeCron(), new SopInstNodeJob(),
sop.getInst().getInstName() + "-" + node.getNodeName(), paramJson, enabled);
}
// 执行本节点
public void handleNode(SopInstNode node) {
/** 实例节点前置节点id */
private Set<Integer> preIds;
}
}
package cn.com.glsx.process.job.instance;
import java.util.Set;
import com.alibaba.nacos.shaded.com.google.common.collect.Sets;
import lombok.Data;
@Data
public class SopInstNodeParam {
/** 实例节点id */
private Integer instNodeId;
/** 实例节点前置节点id */
private Set<Integer> preIds = Sets.newHashSet();
/** 已完成的前置节点,当所有前置节点已完成时,触发本任务 */
private Set<Integer> finishedIds = Sets.newHashSet();
}
\ No newline at end of file
package cn.com.glsx.process.modules.controller;
import com.alibaba.fastjson.JSON;
public class Controller {
public JSON execute(JSON param) {
System.out.println("测试java");
return param;
}
}
......@@ -43,7 +43,7 @@ public class TestJobController {
@PostMapping("/jobtestdel")
@Operation(summary = "动态任务删除", description = "动态任务删除")
public void deltest(@RequestParam("jobName") String jobName) {
dynamicTaskAdd.removeJob(jobName);
}
}
......@@ -12,7 +12,6 @@ import org.springframework.stereotype.Service;
import com.alibaba.nacos.shaded.com.google.common.collect.Maps;
import com.alibaba.nacos.shaded.com.google.common.collect.Sets;
import com.glsx.plat.jwt.util.JwtUtils;
import cn.com.glsx.process.modules.entity.SopInst;
import cn.com.glsx.process.modules.entity.SopInstBatch;
......@@ -49,9 +48,6 @@ public class SopService {
private StringRedisTemplate stringRedisTemplate;
@Resource
private JwtUtils jwtUtils;
@Resource
private SopTplMapper tplMapper;
@Resource
......@@ -85,6 +81,11 @@ public class SopService {
return all;
}
public SopStruct loadSopByInstNodeId(Integer instNodeId) {
SopInstNode instNode = instNodeMapper.selectByPrimaryKey(instNodeId);
return loadSop(instNode.getInstId());
}
public SopStruct loadSop(String instId) {
SopStruct sop = new SopStruct();
......@@ -137,4 +138,53 @@ public class SopService {
return sop;
}
public void execute() {
// String flowInstanceId = Tools.genFlowInstanceId(session.getId(), webStruct.getFlowId());
//
// ConcurrentHashMap<String, RunResult> runResultMap = new ConcurrentHashMap<String, RunResult>();
// FlowRunSort flowRunSort = new FlowRunSort();
// ExecuteStruct executeStruct = new ExecuteStruct();
// executeStruct.setMcgWebScoketCode(webStruct.getMcgWebScoketCode());
// executeStruct.setFlowId(webStruct.getFlowId());
// executeStruct.setFlowInstanceId(flowInstanceId);
// executeStruct.setDataMap(flowRunSort.init(flowStruct));
// executeStruct.setOrders(flowRunSort.getFlowSort());
// executeStruct.setRunResultMap(runResultMap);
// executeStruct.setSession(session);
// executeStruct.setTopology(curTopology);
// executeStruct.setSubFlag(subFlag);
// executeStruct.setRunStatus(runStatus);
//
// notifyBody.setContent("【" + curTopology.getName() + "】流程执行开始!");
// notifyBody.setType(LogTypeEnum.INFO.getValue());
// message.setBody(notifyBody);
// MessagePlugin.push(webStruct.getMcgWebScoketCode(), session.getId(), message);
//
// try {
// FlowTask flowTask = new FlowTask(webStruct.getMcgWebScoketCode(), session.getId(), executeStruct, subFlag);
//
// FlowInstancesUtils.executeStructMap.put(flowInstanceId, executeStruct);
// Future<RunStatus> future = ThreadPoolUtils.FLOW_WORK_EXECUTOR.submit(flowTask);
//
// FlowInstancesUtils.executeStructMap.get(flowInstanceId).getFlowTaskFutureList().add(future);
// if(subFlag) {
//
// String subFlowInstanceId = Tools.genFlowInstanceId(session.getId(), parentFlowId);
// ExecuteStruct parentExecuteStruct = FlowInstancesUtils.executeStructMap.get(subFlowInstanceId);
// executeStruct.setParentParam(parentParam);
// parentExecuteStruct.setChildExecuteStruct(executeStruct);
// }
// runStatus = future.get();
// logger.debug("流程:{}, 执行结果:{}", JSON.toJSONString(curTopology), JSON.toJSONString(runStatus));
// return runStatus;
//
// } catch(CancellationException e) {
// executeStruct.getRunStatus().setInterrupt(true);
// logger.error("流程执行中断,抛出CancellationException,异常信息:", e);
// } catch (InterruptedException e) {
// executeStruct.getRunStatus().setInterrupt(true);
// logger.error("流程执行中断,抛出InterruptedException,异常信息:", e);
// }
}
}
package cn.com.glsx.process.modules.sop;
import cn.hutool.json.JSON;
/**
* 节点执行器
*
* @author kome
* @date 2023年9月10日 下午3:18:31
*/
public abstract class SopNodeExecutor {
/**
* 判断依赖的执行条件是否都满足了
*
* @return
*/
public abstract boolean executeAble();
public abstract void prepare();
public abstract JSON execute(JSON param);
}
......@@ -16,9 +16,6 @@
package cn.com.glsx.process.plugin.java;
import cn.com.glsx.process.common.constant.Constants;
import javax.tools.*;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
......@@ -27,18 +24,29 @@ import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.ToolProvider;
import cn.com.glsx.process.common.constant.Constants;
public class DynamicEngine {
private static DynamicEngine ourInstance = new DynamicEngine();
public static DynamicEngine getInstance() {
return ourInstance;
}
private URLClassLoader parentClassLoader;
private String classpath;
private DynamicEngine() {
this.parentClassLoader = (URLClassLoader) this.getClass().getClassLoader();
this.buildClassPath();
}
private void buildClassPath() {
this.classpath = null;
StringBuilder sb = new StringBuilder();
......@@ -51,6 +59,7 @@ public class DynamicEngine {
/**
* 调用类方法
*
* @param cls 类
* @param methodName 方法名
* @param paramsCls 方法参数类型
......@@ -63,7 +72,8 @@ public class DynamicEngine {
* @throws InvocationTargetException
* @throws IllegalArgumentException
*/
public Object invoke(Class<?> cls, String methodName, Class<?>[] paramsCls, Object[] params) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
public Object invoke(Class<?> cls, String methodName, Class<?>[] paramsCls, Object[] params) throws NoSuchMethodException, SecurityException,
InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Object result = null;
Method method = cls.getDeclaredMethod(methodName, paramsCls);
Object obj = cls.newInstance();
......@@ -71,7 +81,7 @@ public class DynamicEngine {
return result;
}
public Object execute(String fullClassName, String javaCode, String method, Class<?>[] paramsCls,Object[] params) throws Exception {
public Object execute(String fullClassName, String javaCode, String method, Class<?>[] paramsCls, Object[] params) throws Exception {
Object result = null;
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
......@@ -92,7 +102,7 @@ public class DynamicEngine {
if (success) {
JavaClassObject jco = fileManager.getJavaClassObject();
DynamicClassLoader dynamicClassLoader = new DynamicClassLoader(this.parentClassLoader);
Class<?> clazz = dynamicClassLoader.loadClass(fullClassName,jco);
Class<?> clazz = dynamicClassLoader.loadClass(fullClassName, jco);
result = invoke(clazz, method, paramsCls, params);
// instance = clazz.newInstance();
......@@ -122,4 +132,3 @@ public class DynamicEngine {
return res.toString();
}
}
......@@ -3,9 +3,21 @@ server.servlet.context-path=/process
# database
spring.datasource.url=jdbc:mysql://192.168.3.222:3308/platform_process_dev?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=manager
spring.datasource.username=user_zhouhb
spring.datasource.password=WoWP7N1u
elaticjob.zookeeper.server-lists=192.168.3.101:2181
elaticjob.zookeeper.dynamiczk=192.168.3.101:2181
elaticjob.zookeeper.namespace=glsx_sop
xxl.job.admin.addresses=http://127.0.0.1:8080/xxl-job-admin
xxl.job.accessToken=default_token
xxl.job.executor.appname=xxl-job-executor-test
xxl.job.executor.address=
xxl.job.executor.ip=127.0.0.1
xxl.job.executor.port=8080
xxl.job.executor.logpath=/data/applogs/xxl-job/jobhandler
xxl.job.executor.logretentiondays=30
xxl.job.executor.groupId=1
......@@ -2,6 +2,13 @@ spring.application.name=platform-process
logging.path=/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log
### 禁用nacos,启用本地配置文件
#spring.cloud.nacos.config.enabled=false
#spring.cloud.nacos.config.refresh-enabled=false
#spring.cloud.nacos.discovery.enabled=false
#spring.cloud.nacos.discovery.instance-enabled=false
spring.cloud.nacos.config.server-addr=192.168.0.63:8868
spring.cloud.nacos.config.group=PLATFORM_GROUP
......@@ -18,3 +25,7 @@ spring.cloud.nacos.config.shared-configs[1].data-id=platform-share-dev.propertie
spring.cloud.nacos.config.shared-configs[1].refresh=true
#@PropertySource("file:${env.properties.path}/${env.profile}/application.properties")
#spring.config.location=application.properties_standalone
package cn.com.glsx.cn.com.glsx.util;
import java.util.Map;
import java.util.Set;
import com.alibaba.nacos.shaded.com.google.common.collect.Sets;
import com.fasterxml.jackson.core.type.TypeReference;
/**
* 遍历流程所有节点
*
* @author kome
* @date 2023年9月13日 下午3:24:28
*/
public class FlowSortUtil {
public static void main(String[] args) {
String json = "{\"1\":{\"value\":[10],\"key\":[]},\"2\":{\"value\":[3,4],\"key\":[10]},\"3\":{\"value\":[9],\"key\":[2]},\"4\":{\"value\":[9],\"key\":[2]},\"5\":{\"value\":[9],\"key\":[8]},\"6\":{\"value\":[9],\"key\":[8]},\"7\":{\"value\":[],\"key\":[9]},\"8\":{\"value\":[5,6],\"key\":[10]},\"9\":{\"value\":[7],\"key\":[3,4,5,6]},\"10\":{\"value\":[2,8],\"key\":[1]}}";
Map<Integer, Pair<Set<Integer>, Set<Integer>>> instLinkMap = JacksonUtils.fromJson(json,
new TypeReference<Map<Integer, Pair<Set<Integer>, Set<Integer>>>>() {
});
Set<Integer> keys = Sets.newHashSet();
int i = 0;
while (keys.size() < instLinkMap.keySet().size()) {
Set<Integer> sets = instLinkMap.keySet();
for (Integer key : sets) {
// System.out.println("i:" + i++);
Pair<Set<Integer>, Set<Integer>> pair = instLinkMap.get(key);
if (!keys.contains(key)) {
// 第一个节点:直接执行
if (pair.getKey().isEmpty()) {
keys.add(key);
System.out.println(key);
continue;
}
// 非第一个节点:判断前置节点
if (keys.containsAll(pair.getKey())) {
keys.add(key);
System.out.println(key);
continue;
}
} else {
// 进入后置节点
sets = pair.getValue();
}
}
}
}
}
package cn.com.glsx.cn.com.glsx.util;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Pair<K, V> implements Serializable {
private K key;
private V value;
public Pair() {
}
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
/**
* @return the key
*/
public final K getKey() {
return key;
}
/**
* @param key the key to set
*/
public final void setKey(K key) {
this.key = key;
}
/**
* @return the value
*/
public final V getValue() {
return value;
}
/**
* @param value the value to set
*/
public final void setValue(V value) {
this.value = value;
}
/**
* @return
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "[" + key + " : " + value + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key == null) ? 0 : key.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Pair<?, ?> other = (Pair<?, ?>) obj;
if (key == null) {
if (other.key != null) {
return false;
}
} else if (!key.equals(other.key)) {
return false;
}
if (value == null) {
if (other.value != null) {
return false;
}
} else if (!value.equals(other.value)) {
return false;
}
return true;
}
public K first() {
return getKey();
}
public V second() {
return getValue();
}
}
\ No newline at end of file
This diff could not be displayed because it is too large.
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!