巧用liteflow,告别if else,SpringBoot整合liteflow

假设有一个三个原子业务,吃饭、喝水、刷牙。
现在有三个场景,分别是
场景A: 吃饭->刷牙->喝水

官网地址:https://liteflow.cc/

1.添加依赖:

<dependency>
  <groupId>com.yomahub</groupId>
  <artifactId>liteflow-spring-boot-starter</artifactId>
  <version>2.11.4.2</version>
</dependency>

2.application.yml

liteflow:
  rule-source: flow.el.xml

3.resources下创建flow.el.xml

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

创建3个组件:ABC
组件A:

 @Component("a")
    public class ComponentA  extends NodeComponent {
        @Override
        public void process() throws Exception {
            //设置上下下文
            DefaultContext context = this.getContextBean(DefaultContext.class);
            context.setData("key","你好!!!!");
            System.out.println("吃饭");
        }
    }

组件B:

@Component("b")
public class ComponentB extends NodeComponent {
    @Override
    public void process() throws Exception {
        System.out.println("刷牙");
    }
}

组件C:

@Component("c")
public class ComponentC extends NodeComponent {
    @Override
    public void process() throws Exception {
        System.out.println("喝水");
    }
}

测试:

    @PostMapping("testLiteFlow")
    public void test1() {
        LiteflowResponse response = flowExecutor.execute2Resp("chain1", "arg");
        if (response.isSuccess()) {
            System.out.println("执行成功!");
        }
        //异常
        Exception e = response.getCause();
        DefaultContext contextBean = response.getContextBean(DefaultContext.class);
        //取出上下下文
        Object key = contextBean.getData("key");
    }

巧用liteflow,告别if else,SpringBoot整合liteflow_第1张图片
上下文
//设置上下下文

DefaultContext context = this.getContextBean(DefaultContext.class);
context.setData("key","你好!!!!");

取出上下文:

DefaultContext contextBean = response.getContextBean(DefaultContext.class);
 //取出上下下文
 Object key = contextBean.getData("key");
也可以自己定义Context

异常

 //异常
Exception e = response.getCause();

可以随意组合业务:
巧用liteflow,告别if else,SpringBoot整合liteflow_第2张图片

你可能感兴趣的:(实用案例,spring,boot,后端,java)