Location>code7788 >text

Process Orchestration LiteFlow - Business Code Decoupling

Popularity:799 ℃/2024-11-08 00:09:59

LiteFlow really hate each other ah, before doing a lot of systems, will use a variety of if else, switch these to solve the problems raised by different business parties, and sometimes have to "cut a branch" to engage in these additional things, the code made a mess, no readability. LiteFlow was born for decoupling logic, born for orchestration, after using LiteFlow, you will find that building a low-coupling, flexible system will become easy!

In addition, LiteFlow and Activiti are not the same thing, but are oriented to different usage scenarios and needs. LiteFlow is more lightweight and flexible, suitable for simple process management and dynamic configuration scenarios; while Activiti is a comprehensive BPM engine, suitable for complex business process management and task management scenarios. According to the specific business requirements, you can choose the right tool to realize process orchestration.

contexts

Previously done a data distribution system, need to consume kafka data, downstream there are different businesses, each business may have common places, there are also different places, after all kinds of processing, the final data distribution to the downstream inside. In order to simplify the code for easy understanding, we define 4 Handler (A, B, C, D), and then there are 3 different businesses, need to go through different Handler, the whole process is as follows.

image-20241108000137572

If we were to implement appeal functionality in a code, our first thought might be tochain-of-responsibility design pattern, one link per business, in Spring, similar to the following code:

public abstract class Handler {
    abstract void handler(Request request);
}

@Component
@Slf4j
public class HandlerA extends Handler{
    @Override
    public void handler(Request request) {
        ("processing unit1");
    }
}

@Component
@Slf4j
public class HandlerB extends Handler {
    @Override
    public void handler(Request request) {
        ("processing unit2");
    }
}

@Component
@Slf4j
public class HandlerC extends Handler{
    @Override
    public void handler(Request request) {
        ("processing unit3");
    }
}
@Component
@Slf4j
public class HandlerD extends Handler{
    @Override
    public void handler(Request request) {
        ("processing unit4");
    }
}

//Then we define an enum class,用来配置不同业务需要经历过的processing unit。
public enum HandleBuz {
    Business_1(HandlerA,HandlerB),
    Business_2(HandlerB,HandlerC),
    Business_3(HandlerA,HandlerD);
    public final Class<? extends Handler>[] processors;
    public HandleBuz(Class<? extends Handler>[] processors){
        =processors;
    }    
    public void handle(){
        for (Handler handler : processors) {
            (xxx);
        }
    }

}

By configuring the chain of responsibility, it is possible to flexibly combine processing objects, realize different processing flows, and dynamically change the order of processing at runtime, since the chain of responsibility model follows theopening and closing principleThe new handler can be added to the chain of responsibility at any time without modifying the existing code, which provides good scalability. However, in practice, it is not possible to achieve complete decoupling in the face of various requirements, such asFor HandlerA, if both Business 1 and Business 2 have customized requirements (ad hoc or long-term requirements from product mentions)If you want to use if else in HandlerA, or if you want to add HandlerA_1 and HandlerA_2, you're going to need a lot of features, and you're going to end up making your code less and less readable.

I. Why the need for process choreography

LiteFlow open source by Baidu , focusing on logic-driven process orchestration , rapid construction and execution of business processes through componentization , effectively decoupled complex business logic . It is lightweight , fast , stable and can be orchestrated , in the business process management , rules engine , workflow , order processing , data processing , microservices orchestration and intelligent process management and other areas have a wide range of application prospects.

img

II. What problems it can solve

For most of the constantly iterating code, the historical code plus the need to face all kinds of requirements, the code will become more and more difficult to maintain, and even become a mountain of shit. We are thinking of constantly decoupling, constantly cutting and splitting, but also to take into account the new requirements, for fear of the butterfly effect leading to big failures, liteflow can help us in decoupling a little clearer.
(1) Complex business process organization and management
In application scenarios where the business logic is often very complex, involving the execution of multiple steps with complex dependencies between them, LiteFlow can help developers define and manage these processes through a combination of configuration and code.
(2) Dynamic configuration of processes
LiteFlow allows processes to be dynamically modified via configuration files or databases without the need to change code. This means that new processes can be quickly adapted to different business needs and released without the need to redeploy the application.
(3) Multiplexing and decoupling of process nodes
When using LiteFlow, each business step can be defined as an independent node, which can be independently developed, tested and maintained, and reused in multiple processes. In this way, the reuse and decoupling of business logic can be realized and the maintainability of the code can be improved.
(4) Node status and error handling
LiteFlow provides rich node state management and error handling mechanisms that allow developers to catch and handle exceptions during process execution to ensure system stability and robustness.
(5) Highly scalable and customizable
LiteFlow is highly scalable, developers can customize nodes, components and plug-ins according to the specific needs of their business to meet the requirements of complex scenarios.

Here are some sample scenarios where LiteFlow is actually used:
(1)Order Processing System: In e-commerce systems, order processing involves multiple steps, such as inventory checking, payment processing, order confirmation, and shipping, etc. LiteFlow helps to separate these steps into independent implementations, which are then choreographed for execution by a process engine.
(2)Approval Process: In an organization, approval processes typically include multiple nodes (e.g., request, approval, review, archive, etc.), and there may be conditions and dependencies between these nodes.LiteFlow can help dynamically configure and manage these processes to improve approval efficiency.
(3)marketing campaign: In some marketing campaigns, different campaign segments and logic may vary depending on user behavior and external conditions. LiteFlow can help achieve flexible campaign rule configuration and execution.

III. LiteFlow after transformation

First define and implement some components to ensure that SpringBoot will scan for them and register them into the context.

@Slf4j
@LiteflowComponent("a")
public class HandlerA extends NodeComponent {
    @Override
    public void process() throws Exception {
        Customizer contextBean = ();
    }
}

@Slf4j
@LiteflowComponent("b")
public class HandlerB extends NodeComponent {
    @Override
    public void process() throws Exception {
        Customizer contextBean = ();
    }
}

@Slf4j
@LiteflowComponent("c")
public class HandlerC extends NodeComponent {
    @Override
    public void process() throws Exception {
        Customizer contextBean = ();
    }
}

@Slf4j
@LiteflowComponent("d")
public class HandlerD extends NodeComponent {
    @Override
    public void process() throws Exception {
        Customizer contextBean = ();
    }
}

In the meantime, you'll have to add theconfig/Define the rules in:

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

Finally, when consuming kafka, first define a ruleChainMap that is used to determine which chain to go to, which component, etc. based on a unique id (business id or message id), or even define method-level components.

    private Map<Integer, String> ruleChainMap = new HashMap<>();
    @Resource
    private FlowExecutor flowExecutor;

    @PostConstruct
    private void init() {
        (1, "professional work1");
        (2, "professional work2");
        (3, "professional work3");
    }

    @KafkaListener(topics = "xxxx")
    public void common(List<ConsumerRecord<String, String>> records) {
        for (ConsumerRecord<String, String> record : records) {
            ...
            String chainName = ("uniqueid(can berecordinner,It is also possible to globally define theid)");
            LiteflowResponse response = flowExecutor.execute2Resp(chainName, xxx, xxx, new TempContext());
        }
    }

Due to the relationship of space, here no longer explain how to pass the context of the relationship, you can go to the official website to study it. In addition, the above example is simplified, if you think it is not enough image, you can look at the actual business below. If you don't use liteflow, you may have to add a variety of if else in the main process code, and even change a small piece of the follow-up do not know if there is an impact on other places.

image-20241108000231371

summarize

Subsequently, if the face of the product manager "from a big leader of an idea, I do not know whether the follow-up will continue to do it, anyway, do it first," this kind of demand, you can define a LiteFlow component, not pollute the mainstream process of the code, the subsequent downstream of the deletion of can be pleasing to the eye.

Documentation & Reference

1. [Tencent Document] Business Processing Complexity/flowchart/DZVFURmhCb0JFUHFD
2. [Tencent Document] Business Processing Complexity 2/flowchart/DZXVOaUV5VGRtc3ZD
3.An article to understand the design patterns - chain of responsibility pattern
4.LiteFlow Official Website