写在前面

这儿只介绍liteflow的简略根底运用以及作者对liteflow进行可视化扩展的相关论述

一、布景及意义

布景:关于具有杂乱事务逻辑的体系承载着核心事务逻辑,这些核心事务逻辑触及内部逻辑运算,缓存操作,耐久化操作,外部资源调取,内部其他体系RPC调用等等。项目几经易手,保护的本钱就会越来越高。各种硬代码判断,分支条件越来越多。代码的抽象,复用率也越来越低,各个模块之间的耦合度很高。一小段逻辑的变动,会影响到其他模块,需求进行完好回归测试来验证。如要灵敏改动事务流程的顺序,则要进行代码大改动进行抽象,从头写办法。实时热改变事务流程,几乎很难完成

意义:逻辑解耦、进步扩展性、下降保护本钱、才能充分复用、流程灵敏编列

二、常用流程编列框架

liteflow(开源) asyncTool(开源) JDEasyFlow(开源) disruptor
介绍 LiteFlow是一个十分强壮的现代化的规矩引擎框架,交融了编列特性和规矩引擎的一切特性。假如你要对杂乱事务逻辑进行新写或许重构,用LiteFlow最合适不过。它是一个编列式的规矩引擎框架,组件编列,帮助解耦事务代码,让每一个事务片段都是一个组件。 处理恣意的多线程并行、串行、堵塞、依靠、回调的并发框架,可以恣意组合各线程的履行顺序,带全链路回调和超时控制。 通用流程编列技术组件,适用于服务编列、工作流、审批流等场景
地址 liteflow.yomahub.com/ gitee.com/jd-platform… developer.jdcloud.com/article/260…
优点 杂乱事务流程编列、社区老练活跃 根据jdk8 CompletableFuture、轻量级 简略、灵敏、易扩展 根据出产-消费模型、无锁设计
缺点 开源框架较重,有必定学习本钱 新框架稳定性待验证 较为底层,针对事务场景需求二次封装
示例 gitee.com/bryan31/lit…

三、liteflow根底运用

1.增加依靠jar包

<dependency>
	<groupId>com.yomahub</groupId>
    <artifactId>liteflow-spring</artifactId>
	<version>2.10.4</version>
</dependency>

2.界说组件

界说组件和完成某些组件,注册进上下文

@Component("a")
public class ACmp extends NodeComponent {
    @Override
    public void process() {
        //do your business
    }
}

3.装备

增加对应的装备类及装备文件

Spring xml中的装备

<context:component-scan base-package="com.yomahub.flowtest.components" />
<bean id="springAware" class="com.yomahub.liteflow.spi.spring.SpringAware"/>
<bean class="com.yomahub.liteflow.spring.ComponentScanner"/>
<bean id="liteflowConfig" class="com.yomahub.liteflow.property.LiteflowConfig">
    <property name="ruleSource" value="config/flow.el.xml"/>
</bean>
<bean id="flowExecutor" class="com.yomahub.liteflow.core.FlowExecutor">
    <property name="liteflowConfig" ref="liteflowConfig"/>
</bean>
<!-- 假如上述enableLog为false,下面这段也可以省略 -->
<bean class="com.yomahub.liteflow.monitor.MonitorBus">
    <property name="liteflowConfig" ref="liteflowConfig"/>
</bean>

4.规矩文件的界说

–流程的界说(第3步中liteflowConfig指定了规矩文件为config/flow.xml),所以需求在resources下新建文件夹config,在新建flow.xml文件,装备要界说的流程

<?xml version="1.0" encoding="UTF-8"?>
<flow>
    <chain name="chain1">
        THEN(a, b, c)
    </chain>
</flow>

5.履行

编列好的流程,在需求履行的当地注入FlowExecutor,履行execute2Resp

@Component
public class YourClass{
    @Resource
    private FlowExecutor flowExecutor;
    @Test
    public void testConfig(){
        LiteflowResponse response = flowExecutor.execute2Resp("chain1", "arg");
    }
}

四、liteflow在实践中的运用

这儿弱化背后的实践事务只展现作者在实践中的运用事例

1.增加依靠jar包

    <properties>
        <liteflow-spring.version>2.8.0</liteflow-spring.version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.yomahub</groupId>
                <artifactId>liteflow-spring</artifactId>
                <version>${liteflow-spring.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

2.界说组件

界说组件和完成某些组件,注册进上下文

@LiteflowComponent("checkRealNameAuthCmp")
@LiteflowCmpDefine
public class CheckRealNameAuthCmp {
    private static final Logger log = LoggerFactory.getLogger(CheckRealNameAuthCmp.class);
    @LiteflowMethod(LiteFlowMethodEnum.PROCESS)
    public void process(NodeComponent nodeComponent) throws Exception {
       // 获取恳求参数
       GeneratePolicyRightsParam generatePolicyRightsParam = nodeComponent.getSlot().getRequestData();
        // 假如pin为空则结束流程
       if (generatePolicyRightsParam == null || StringUtil.isEmpty(generatePolicyRightsParam.getUserPin())) {
                log.info("CheckRealNameAuthCmp -> process end, nodeComponent={},pin is null.", JsonUtil.toJSONString(nodeComponent));
                nodeComponent.setIsEnd(true);
            }
      //封装设置流程编列上下文信息
      GenerateRightsContext generateRightsContext = nodeComponent.getContextBean(GenerateRightsContext.class);
            generateRightsContext.setGeneratePolicyRightsParam(generatePolicyRightsParam);
    }
}

LiteflowComponent:liteflow.yomahub.com/pages/v2.8.…

LiteflowCmpDefine:liteflow.yomahub.com/pages/v2.8.…

3.装备

增加对应的装备类及装备文件

Spring xml中的装备

spring-config.xml

 <import resource="classpath*:spring/spring-config-liteflow.xml"/>

spring-config-liteflow.xml

    <bean id="springAware" class="com.yomahub.liteflow.spi.spring.SpringAware"/>
    <bean id="springComponentScaner" class="com.yomahub.liteflow.spring.ComponentScanner"/>
    <!-- 注入liteflow的装备文件 -->
    <bean id="liteflowConfig" class="com.yomahub.liteflow.property.LiteflowConfig">
        <property name="ruleSource" value="liteflow/flow.xml"/>
    </bean>
    <!-- 注入liteflow的履行引擎 -->
    <bean id="flowExecutor" class="com.yomahub.liteflow.core.FlowExecutor">
        <property name="liteflowConfig" ref="liteflowConfig"/>
    </bean>
    <!-- 注入liteflow的MonitorBus-->
    <bean class="com.yomahub.liteflow.monitor.MonitorBus">
        <constructor-arg ref="liteflowConfig"/>
        <property name="liteflowConfig" ref="liteflowConfig"/>
    </bean>

4.规矩文件的界说

–流程的界说(第3步中liteflowConfig指定了规矩文件为liteflow/flow.xml),所以需求在resources下新建文件夹liteflow,在新建flow.xml文件,装备要界说的流程

flow.xml

<?xml version="1.0" encoding="UTF-8"?>
<flow>
    <!-- liteflow流程编列:生成(发放)保单权益-->
    <chain name="sendPolicyRightsChain">
        <when value="checkRealNameAuthCmp"/>
        <then value="checkNewPolicyRightsCmp"/>
        <then value="getPolicyInfoCmp"/>
        <then value="policyMatchServiceRuleCmp"/>
        <then value="initPolicyRightsDataCmp"/>
        <then value="creatPlanGantRightsDataCmp"/>
        <then value="asyncFullFillCmp"/>
    </chain>
</flow>

5.履行

履行编列好的流程,在需求履行的当地注入FlowExecutor,履行execute2Resp

 @Resource
 private FlowExecutor flowExecutor;
public Boolean sendPolicyRights(GeneratePolicyRightsParam generatePolicyRightsParam) {
      //todo 入参和上下文不能混用,通用信息用map
      LiteflowResponse response = flowExecutor.execute2Resp("sendPolicyRightsChain", generatePolicyRightsParam, GenerateRightsContext.class,GenerateRightsContext.class);
}

五、liteflow才能扩展(可视化)

liteflowt供给了流程编列的才能,只要研制人员可以了解这内在的流程编列意义,关于其他产品或许事务并不能直观的了解当时的事务流程,可视化并不友爱。这时咱们如何让当时的流程可视化呢?编写一个页面直接读取装备文件flow.xml进行显现,这是没有意义的。有意义的是咱们可以对组件进行可视化、对流程可视化、对流程编列可视化。

1、思维

供给新的jar包,获取到事务体系声名的组件、流程、显现流程和组件、供给编列才能。

阐明:

1、小工具jar包为可视化流程编列小工具,首要供给获取事务体系声明的组件、保存的流程、进行流程可视化展现、进行流程编列可视化等,运用liteflow-util标识差异于事务体系。

2、事务体系为组件声明、流程履行、事务逻辑体系,运用liteflow-test标识

2、完成

2.1获取特定的类或办法

如何从liteflow-util中获取liteflow-test中声明的组件

2.1.1获取上下文环境

ApplicationContextAware

当一个bean的属性初始化后会回调到setApplicationContext,然后设置运用上下文。

public interface ApplicationContextAware extends Aware {
	/**
	 * Set the ApplicationContext that this object runs in.
	 * Normally this call will be used to initialize the object.
	 * 
Invoked after population of normal bean properties but before an init callback such
	 * as {@link org.springframework.beans.factory.InitializingBean#afterPropertiesSet()}
	 * or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},
	 * {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and
	 * {@link MessageSourceAware}, if applicable.
	 * @param applicationContext the ApplicationContext object to be used by this object
	 * @throws ApplicationContextException in case of context initialization errors
	 * @throws BeansException if thrown by application context methods
	 * @see org.springframework.beans.factory.BeanInitializationException
	 */
	void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}

在liteflow-util中运用一个类来完成ApplicationContextAware,然后获取到liteflow-test(依靠当时jar包的运用)的上下文环境

@Configuration
public class LiteFlowApplicationContext implements ApplicationContextAware {
   private static ApplicationContext controllerApplicationContext;
   @Override
   public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
      System.out.println("applicationContext = " + applicationContext);
      LiteFlowApplicationContext.controllerApplicationContext=applicationContext;
   }
   public static ApplicationContext getControllerApplicationContext() {
      return controllerApplicationContext;
   }
}
2.1.2从上下文获取类

在liteflow-util中根据上下文环境获取组件类这儿的重点是Map<String, Object> mvcObjects = context.getBeansWithAnnotation(Service.class);

@Slf4j
public class ReferenceManager {
    private static Map<Class<?>, Object> interfaceMapRef = new ConcurrentHashMap<Class<?>, Object>();
    private static ReferenceManager instance;
    private ReferenceManager() {
    }
    public synchronized static ReferenceManager getInstance() {
        if (null != instance) {
            return instance;
        }
        instance = new ReferenceManager();
        ApplicationContext controllerContext = LiteFlowApplicationContext.getControllerApplicationContext();
        interfaceMapInit(controllerContext);
        return instance;
    }
    private static void interfaceMapInit(ApplicationContext context) {
        try {
            Map<String, Object> objects = Maps.newHashMapWithExpectedSize(64);
            //优化 答应 ServiceBean 被MVC容器扫描
            Map<String, Object> mvcObjects = context.getBeansWithAnnotation(Service.class);
            objects.putAll(mvcObjects);
            if (objects == null || objects.size() == 0) {
                return;
            }
            for (Entry<String, Object> entry : objects.entrySet()) {
                /**
                 * 获取署理目标的原目标
                 * 由于 jdk 动态署理经过接口
                 */
                Object objectImplProxy = entry.getValue();
                Object objectImpl = AopTargetUtils.getTarget(objectImplProxy);
                Class objectImplClass = objectImpl.getClass();
                if (objectImplClass.getInterfaces().length > 0) {
                    /**
                     * 规则 每个interface 只对应 一个完成类
                     * 假如 多个类完成了该接口 接口列表中只 显现第一个完成类
                     */
                    Class interfaceClass = objectImplClass.getInterfaces()[0];
                    Object object = interfaceMapRef.get(interfaceClass);
                    if (object == null) {
                        interfaceMapRef.put(interfaceClass, objectImpl);
                    } else {
                    }
                } else {
                }
            }
        } catch (Exception e) {
        }
    }
    public Map<Class<?>, Object> getInterfaceMapRef() {
        return interfaceMapRef;
    }
}
@Component
public class ServiceScanner {
    public Set<Class<?>> classes() {
        return interfaceMapRef().keySet();
    }
    public Map<Class<?>, Object> interfaceMapRef() {
        return ReferenceManager.getInstance().getInterfaceMapRef();
    }
}
public class AopTargetUtils {
	/**
	 * 获取 目标目标
	 * @param proxy 署理目标
	 * @return
	 * @throws Exception
	 */
	public static Object getTarget(Object proxy) throws Exception {
		if(!AopUtils.isAopProxy(proxy)) {
			return proxy;//不是署理目标
		}
		if(AopUtils.isJdkDynamicProxy(proxy)) {
			return getJdkDynamicProxyTargetObject(proxy);
		} else { //cglib
			return getCglibProxyTargetObject(proxy);
		}
	}
	private static Object getCglibProxyTargetObject(Object proxy) {
		try{
			Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");
			h.setAccessible(true);
			Object dynamicAdvisedInterceptor = h.get(proxy);
			Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
			advised.setAccessible(true);
			Object target = ((AdvisedSupport) advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();
			return target;
		} catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	private static Object getJdkDynamicProxyTargetObject(Object proxy) {
		try{
			Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
			h.setAccessible(true);
			AopProxy aopProxy = (AopProxy) h.get(proxy);
			Field advised = aopProxy.getClass().getDeclaredField("advised");
			advised.setAccessible(true);
			Object target = ((AdvisedSupport) advised.get(aopProxy)).getTargetSource().getTarget();
			return target;
		} catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
}

2.2拜访liteflow-util页面

如何在liteflow-test里拜访到liteflow-util包里的页面并展现

(1)在liteflow-util内编写一个Servlet类,直接承继HttpServlet ,重写doGet或许doPost办法

(2)在liteflow-util内将Servlet类装备到web.xml中

(3)在liteflow-util内预备前端的页面(form表单、按钮交互)

(4)在liteflow-test内引进依靠并发动liteflow-test

2.2.1HttpServlet
public class HandServlet extends HttpServlet {
    private static final Logger log = LoggerFactory.getLogger(HandServlet.class);
    private String username = null;
    private String password = null;
    private ServletContext servletContext;
    public HandServlet() {
    }
    @Override
    public void init(ServletConfig config) {
        log.info("HandServlet->init,start");
        this.username = config.getInitParameter("loginUsername");
        this.password = config.getInitParameter("loginPassword");
        this.servletContext = config.getServletContext();
        log.info("HandServlet->init finish");
    }
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String contextPath = request.getContextPath();
        String servletPath = request.getServletPath();
        String requestURI = request.getRequestURI();
        response.setCharacterEncoding("utf-8");
        if (contextPath == null) {
            contextPath = "";
        }
        String uri = contextPath + servletPath;
        String path = requestURI.substring(contextPath.length() + servletPath.length());
        String usernameParam;
        if (!Objects.equals("/submitLogin", path)) {
            if (this.needLogin(request, path)) {
                this.redirect(request, response);
            } else {
                Result result;
                try {
                    result = this.requestHandler(path, request);
                } catch (Throwable var11) {
                    log.error("HandServlet->service,requestHandler error", var11);
                    result = Result.buildFail(var11.getMessage());
                }
                if (null != result) {
                    response.getWriter().print(JSON.toJSONString(result));
                } else {
                    this.returnResourceFile(path, uri, response);
                }
            }
        } else {
            usernameParam = request.getParameter("loginUsername");
            String passwordParam = request.getParameter("loginPassword");
            System.out.println("usernameParam = " + usernameParam);
            System.out.println("passwordParam = " + passwordParam);
//            if (this.username.equals(usernameParam) && this.password.equals(passwordParam)) {
            HttpSession session = request.getSession();
            session.setAttribute("lite-flow", this.username);
            session.setMaxInactiveInterval(300);
            response.getWriter().print(JSON.toJSONString(Result.buildSuccess("success")));
//            } else {
//                response.getWriter().print(JSON.toJSONString(Result.buildFail("用户名或密码错误")));
//            }
        }
    }
    private void redirect(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (request.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            response.getWriter().print(JSON.toJSONString(Result.buildReLogin()));
        } else if (request.getHeader("Accept") != null && request.getHeader("Accept").contains("application/json")) {
            response.getWriter().print(JSON.toJSONString(Result.buildReLogin()));
        } else {
            response.sendRedirect("/lite-flow/login.html");
        }
    }
    private Result requestHandler(String path, HttpServletRequest request) {
        System.out.println("path = " + path);
        System.out.println("request = " + request);
        String initMenu = "/initMenu";
        String liteflow = "/liteflow";
        if (initMenu.equals(path)) {
            Map<String, Object> map = new HashMap(2);
            List<String> classObjectMap = getClassObjectMap();
            classObjectMap.forEach(item -> {
                int i = item.lastIndexOf(".");
                String substring = item.substring(i+1);
                System.out.println("substring = " + substring);
   LiteFlowNodeBuilder.createCommonNode().setId(substring).setName(substring).setClazz(item).build();
            });
            map.put("interfaceMapRef", classObjectMap);
            return Result.buildSuccess(map);
        } else if (liteflow.equals(path)) {
            try {
                try {
                    String postData = this.getPostData(request);
                    log.info("HandServlet -> requestHandler start, postData={}", postData);
                    JSONObject jsonObject = JSONObject.parseObject(postData);
                    JSONArray checkList = jsonObject.getJSONArray("checkList");
                    String chainId = (String) jsonObject.get("chainId");
                    log.info("HandServlet -> requestHandler start, path={},checkList={}", path, checkList);
                    ArrayList arrayList = new ArrayList();
                    checkList.forEach(item -> {
                        String itemStr = (String) item;
                        int i = itemStr.lastIndexOf(".");
                        String substring = itemStr.substring(i+1);
                        arrayList.add(substring);
                    });
                    String str = StringUtils.join(arrayList, ",");
                    log.info("HandServlet -> requestHandler start, str={}", str);
//                    String elss = "THEN(" + str + ")";
//                    log.info("HandServlet -> requestHandler start, elss={}", elss);
                    Condition condition = LiteFlowConditionBuilder.createCondition(ConditionTypeEnum.TYPE_THEN).setValue(str).build();
                    log.info("HandServlet -> requestHandler start, condition={}", condition);
                    LiteFlowChainBuilder.createChain().setChainName(chainId).setCondition(condition).build();
                } catch (Throwable var3) {
                    log.error("HandServlet -> requestHandler exception 未知反常, var3={}", var3);
                }
            } catch (Throwable var3) {
                log.info("MqUtil->haveProducer,error", var3);
            }
            return Result.buildSuccess(false);
        } else {
            return null;
        }
    }
    public String getPostData(HttpServletRequest request) {
        StringBuilder data = new StringBuilder();
        String line;
        BufferedReader reader;
        try {
            reader = request.getReader();
            while (null != (line = reader.readLine())) {
                data.append(line);
            }
        } catch (IOException e) {
            return null;
        }
        return data.toString();
    }
    private List<String> getClassObjectMap() {
        List<String> result = new ArrayList<>();
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        Map<String, ServiceScanner> serviceScannerMap = webApplicationContext.getBeansOfType(ServiceScanner.class);
        ServiceScanner serviceScanner = serviceScannerMap.get("serviceScanner");
        Map<Class<?>, Object> interfaceMapRef = serviceScanner.interfaceMapRef();
        if (null != interfaceMapRef) {
            //排序 一切接口
            List<Map.Entry<Class<?>, Object>> arrayList = new ArrayList<Map.Entry<Class<?>, Object>>(interfaceMapRef.entrySet());
            Collections.sort(arrayList, new Comparator<Map.Entry<Class<?>, Object>>() {
                @Override
                public int compare(Map.Entry<Class<?>, Object> o1, Map.Entry<Class<?>, Object> o2) {
                    return o1.getKey().getSimpleName().compareTo(o2.getKey().getSimpleName());
                }
            });
            //遍历 一切接口
            for (Map.Entry<Class<?>, Object> entry : arrayList) {
                String className = entry.getValue().getClass().getName();
                System.out.println("class = " + className);
                result.add(className);
//                List<Method> interfaceMethodList = Arrays.asList(entry.getKey().getDeclaredMethods());
//                //办法列表排序
//                Collections.sort(interfaceMethodList, new Comparator<Method>() {
//                    @Override
//                    public int compare(Method o1, Method o2) {
//                        return o1.getName().compareTo(o2.getName());
//                    }
//                });
//                for (Method method : interfaceMethodList) {
//                    System.out.println("method = " + method);
//                    System.out.println("methodName = " + method.getName());
//                    System.out.println("methodParameterTypes = " + method.getParameterTypes());
//                    System.out.println("methodReturn = " + method.getReturnType());
//                }
            }
        }
        System.out.println("result = " + result);
        return result;
    }
    private boolean needLogin(HttpServletRequest request, String path) {
        return this.isRequireAuth() && !this.alreadyLogin(request) && !this.checkLoginParam(request) && !"/login.html".equals(path) && !path.startsWith("/css") && !path.startsWith("/js") && !path.startsWith("/img");
    }
    private boolean checkLoginParam(HttpServletRequest request) {
        String usernameParam = request.getParameter("loginUsername");
        String passwordParam = request.getParameter("loginPassword");
        if (null != this.username && null != this.password) {
            return this.username.equals(usernameParam) && this.password.equals(passwordParam);
        } else {
            return false;
        }
    }
    private boolean isRequireAuth() {
        return this.username != null;
    }
    private boolean alreadyLogin(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        return session != null && session.getAttribute("lite-flow") != null;
    }
    private void returnResourceFile(String fileName, String uri, HttpServletResponse response) throws IOException {
        String filePath = this.getFilePath(fileName);
        if (filePath.endsWith(".html")) {
            response.setContentType("text/html; charset=utf-8");
        }
        if (fileName.endsWith(".jpg")) {
            byte[] bytes = Utils.readByteArrayFromResource(filePath);
            if (bytes != null) {
                response.getOutputStream().write(bytes);
            }
        } else {
            String text = Utils.readFromResource(filePath);
            if (text == null) {
                response.sendRedirect(uri + "/login.html");
            } else {
                if (fileName.endsWith(".css")) {
                    response.setContentType("text/css;charset=utf-8");
                } else if (fileName.endsWith(".js")) {
                    response.setContentType("text/javascript;charset=utf-8");
                }
                response.getWriter().write(text);
            }
        }
    }
    private String getFilePath(String fileName) {
        return "view" + fileName;
    }
2.2.2装备web.xml

在liteflow-util内web.xml装备自界说的servlet

    <servlet>
        <servlet-name>handOfLite</servlet-name>
        <servlet-class>com.xx.utils.liteflow.handler.HandServlet</servlet-class>
        <init-param>
            <param-name>loginUsername</param-name>
            <param-value>Username</param-value>
        </init-param>
        <init-param>
            <param-name>loginPassword</param-name>
            <param-value>Password</param-value>
        </init-param>
        <load-on-startup>5</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>handOfLite</servlet-name>
        <url-pattern>/hand-of-lite/*</url-pattern>
    </servlet-mapping>
2.2.3页面预备

在liteflow-util内预备显现组件的页面

流程编排及可视化 | 京东云技术团队

2.2.4拜访页面

在liteflow-test内增加liteflow-util的依靠

<dependency>
    <groupId>com.xx.utils</groupId>
    <artifactId>liteflow</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

发动liteflow-test工程并拜访对应的路径,看到2.2.3预备的页面

流程编排及可视化 | 京东云技术团队

2.3获取组件并回显

2.3.1自界说注解

在liteflow-util内自界说注解,作用安装导入需求的资源类和装备

@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value = { java.lang.annotation.ElementType.TYPE })
@Documented
@Import({LiteFlowApplicationContext.class, FlowExecutor.class, LiteflowConfig.class, IdGeneratorHolder.class})
@ComponentScan(
        basePackages = {"com.xx.utils", "com.xx.utils.liteflow"}
)
public @interface EnableLiteFlow {
}
2.3.2引进jar包依靠

在liteflow-util内引进lite-flow核心依靠

<dependency>
    <groupId>com.yomahub</groupId>
    <artifactId>liteflow-spring</artifactId>
    <version>2.8.3</version>
</dependency>

在liteflow-test内引进liteflow-util依靠

<dependency>
    <groupId>com.xx.utils</groupId>
    <artifactId>liteflow</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>
2.3.3装备liteflow-util

在liteflow-test中运用自界说注解导入需求的装备

@Configuration
@EnableLiteFlow
public class LiteFlowConfig {
}
2.3.4显现组件类

重启liteflow-test,拜访页面显现已获取到的组件集合

流程编排及可视化 | 京东云技术团队

2.4创立新的组件

liteflow-util供给关于的RequestMapping创立和保存node

@RestController
@RequestMapping("/node")
public class NodeController {
    private static final Logger log = LoggerFactory.getLogger(NodeController.class);
    /**
     * 构建一个普通组件
     */
    @RequestMapping("/createCommonNode")
    @ResponseBody
    public Boolean createCommonNode(@RequestBody NodeParam nodeParam) {
        log.info("NodeController -> createCommonNode start, nodeParam={}", nodeParam.toString());
        try {
            //构建一个普通组件
            LiteFlowNodeBuilder.createCommonNode().setId(nodeParam.getId()).setName(nodeParam.getName()).setClazz(nodeParam.getClazz()).build();
            return Boolean.TRUE;
        } catch (Exception e) {
            return Boolean.FALSE;
        }
    }
    /**
     * 构建一个普通条件组件
     */
    @RequestMapping("/createSwitchNode")
    @ResponseBody
    public Boolean createSwitchNode(@RequestBody NodeParam nodeParam) {
        try {
           LiteFlowNodeBuilder.createSwitchNode().setId(nodeParam.getId()).setName(nodeParam.getName()).setClazz(nodeParam.getClazz()).build();
            return Boolean.TRUE;
        } catch (Exception e) {
            return Boolean.FALSE;
        }
    }
}

2.5创立新的流程

liteflow.yomahub.com/pages/v2.8.…

LiteFlowChainELBuilder.createChain().setChainName("chain2").setEL(
  "THEN(a, b, WHEN(c, d))"
).build();

3、全体的总结

其实全体的思维就是供给一个jar包,从这个jar包里可以获取到被依靠工程里的类创立对应的组件、创立流程、保存流程、回显流程、履行流程等,这儿触及springbean的生命周期、上下文环境、httpservlet、自界说注解、反射、前端页面等相关知识的交融运用。

作者:京东健康 马仁喜

来源:京东云开发者社区