springboot整合规则引擎(liteflow)使用
网站:🍤LiteFlow简介 | LiteFlow
规则引擎,定义业务执行逻辑,把公共组件抽出来进行封装。
作用:
- 可以将公有代码抽为组件
- 根据不同的模式走不同的组件流程
- 参数可以在组件之间共享
1、导入依赖
<dependency><groupId>com.yomahub</groupId><artifactId>liteflow-spring-boot-starter</artifactId><version>2.13.1</version>
</dependency>
2、组件定义
@LiteflowComponent("a")
public class ACmp extends NodeComponent {// 走这个流程 通过默认上下文方式@Overridepublic void process() {User user = this.getContextBean(User.class);user.setRealName(user.getRealName()+"A");System.out.println(user);System.out.println("AAA");//do your business}
}
@LiteflowComponent("b")
public class BCmp extends NodeComponent {@Overridepublic void process() {User user = this.getContextBean(User.class);user.setRealName(user.getRealName()+"B");System.out.println(user);System.out.println("BBB");//do your business}// 走这个流程 注解方式@LiteflowMethod(value = LiteFlowMethodEnum.PROCESS,nodeType = NodeTypeEnum.COMMON, nodeId = "b")public void processB(NodeComponent bindCmp,@LiteflowFact("user") User user) {
// User user = bindCmp.getContextBean(User.class);user.setRealName(user.getRealName()+"B2");System.out.println(user);System.out.println("BBB2");}}
@LiteflowComponent("c")
public class CCmp extends NodeComponent {@Overridepublic void process() {User user = this.getContextBean(User.class);user.setRealName(user.getRealName()+"C");System.out.println(user);System.out.println("CCC");}// 走这个流程 NodeComponent获取方式@LiteflowMethod(value = LiteFlowMethodEnum.PROCESS,nodeType = NodeTypeEnum.COMMON, nodeId = "c")public void processB(NodeComponent bindCmp) {User user = bindCmp.getContextBean(User.class);user.setRealName(user.getRealName()+"C2");System.out.println(user);System.out.println("CCC");}
}
3、配置yml、xml
yml
liteflow.rule-source=config/flow.xml
xml配置链路组件
可以定义多条链路,每条链路执行顺序可以定义,就是把需要执行的组件以及顺序排列好,后面业务可以直接调用,同时可以根据需求定义。目前是最简单的一条完整执行链路。
<?xml version="1.0" encoding="UTF-8"?>
<flow><chain name="chain1">THEN(a, c, b);</chain>
</flow>
4、执行调用
启动类加扫描
@SpringBootApplication
//把你定义的组件扫入Spring上下文中
@ComponentScan({"com.xxx.xxx.cmp"})
public class LiteflowExampleApplication {public static void main(String[] args) {SpringApplication.run(LiteflowExampleApplication.class, args);}
}
业务类调用
@Component
public class FlowService{@Resourceprivate FlowExecutor flowExecutor;public void testConfig(){System.out.println("start------------------");User user = new User();user.setRealName("张三");user.setAddIp("1.2.3.4");user.setAddress("中国四川成都");LiteflowResponse response = flowExecutor.execute2Resp("chain1", "arg111111", user);System.out.println("end-----------------------");}
}
5、测试结果
控制台打印参数顺序:
user的RealName为:AC2B2 ,流程是先a 再c 再b