In-depth comparison of rule engines, LiteFlow vs Drools!

Click on “Yao Dao Source Code” above and select “Set as Star”

Does she care about the front wave or the back wave?

A wave that can wave is a good wave!

Update articles every day at 10:33, lose a million bits of hair every day…

Source code boutique column

  • Original | Java 2021 Super God Road, very liver~

  • An open source project with detailed annotations in Chinese

  • RPC framework Dubbo source code analysis

  • Network application framework Netty source code analysis

  • Message middleware RocketMQ source code analysis

  • Database middleware Sharding-JDBC and MyCAT source code analysis

  • Job Scheduling Middleware Elastic-Job Source Code Analysis

  • Distributed transaction middleware TCC-Transaction source code analysis

  • Eureka and Hystrix source code analysis

  • Java Concurrency Source Code

Source: juejin.cn/post/

7155672111481094152

  • Definition of rule engine

  • The similarities and differences between the two frameworks

  • regular expression

  • Data exchange with Java

  • APIs and integrations

  • Intrusive Coupling Comparison

  • learning cost of rules

  • Is there a language plugin

  • storage of rules

  • Can rule changes change the logic in real time

  • Is there an interface form to support

  • Performance of the framework

  • epilogue

Drools is an old-fashioned java rule engine framework. As early as more than ten years ago, when I first started working, I worked in a third-party payment company. At the core payment routing level, I remember using Drools to do it.

What is commendable is that the Drools project still maintains open source and updates after more than ten years.

https://github.com/kiegroup/drools

LiteFlow is also a java rule engine, which was open sourced in 2020. After 2 years of iteration, the functions and features are now very good, very suitable for use in high-complexity core business, while maintaining business flexibility.

https://gitee.com/dromara/liteFlow

In this article, let’s make an in-depth comparison of these two frameworks, what kind of scenarios they are suitable for, what are their similarities and differences, and how expressive they are in the same scenario.

(Drools is based on version 7.6.0, and LiteFlow is based on version 2.9.0)

Although the subject of the topic is the author of the open source project LiteFlow, I have also learned about Drools in the past few days, and try to analyze it from a very objective perspective. The results of many comparisons are based on the feelings after actual use. However, the subject will inevitably have some subjective psychology and one-sided understanding, especially since Drools has now been updated to 8.X.

Definition of rule engine

First of all, I want to clarify the definition of rule engine, because many friends tend to confuse the concepts of rule engine and process engine.

The rule engine is usually embedded in the application components, which realizes the separation of business decisions from the application code, and uses predefined semantic modules to write business decisions. Accept data input, interpret business rules, and make business decisions based on business rules.

To put it simply, the rule engine mainly solves the problem of variable logic and business coupling, and rules drive logic. The logic that was hard-coded in the code in the previous project can be proposed by the rule engine and can be changed at any time.

The process engine realizes the flow between multiple business participants according to some predefined rules, usually involving role information.

To put it simply, the process engine mainly solves the problem of business flow between different roles, such as the leave process and approval process, which often go through multiple roles. Rules drive the flow of roles.

Background management system + user applet based on Spring Boot + MyBatis Plus + Vue & amp; Element, supports RBAC dynamic permissions, multi-tenancy, data permissions, workflow, three-party login, payment, SMS, mall and other functions

  • Project address: https://github.com/YunaiV/ruoyi-vue-pro

  • Video tutorial: https://doc.iocoder.cn/video/

Similarities and differences between the two frameworks

Both Drools and LiteFlow are excellent open source frameworks, both of which can separate the logic in the business. And has its own expression syntax.

But the difference is that Drools emphasizes the regularization of logic fragments. You can write the core variable part into a rule file, which is equivalent to the code originally written in java and now moved to the rule file. The code in the rule file is all hot changeable.

LiteFlow, on the other hand, is designed based on component-based thinking, emphasizing the regularization of components and covering the entire business. The smallest unit of orchestration is a component, and rule files are used to serialize the flow between components. At the same time, LiteFlow also supports fragmented code regularization, because LiteFlow also supports scripting of business logic. Rules support hot changes.

Therefore, the main factors to judge whether a rule engine is qualified are:

  1. Is there any flexible regular expressions to support

  2. Can the linkage between rules and Java be very convenient

  3. Is it convenient to call the API, and how is it integrated with various scene systems?

  4. Intrusive Coupling Comparison

  5. The learning cost of the rules, whether it is easy to use

  6. Is there a language plugin for regular expressions

  7. Can the rules be loosely coupled with the business and stored elsewhere

  8. Can rule changes change the logic in real time

  9. Is there an interface shape to support the use of non-technical personnel

  10. Performance of the framework

The following is a detailed comparison of the expressiveness of the two frameworks from these aspects.

Background management system + user applet based on Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & amp; Element, supporting RBAC dynamic permissions, multi-tenancy, data permissions, workflow, three-party login, payment, SMS, mall and other functions

  • Project address: https://github.com/YunaiV/yudao-cloud

  • Video tutorial: https://doc.iocoder.cn/video/

regular expression

Drools’ regular expressions are the implementation of a rule engine based on Charles Forgy’s RETE algorithm tailored for Java.

The regular expression of Drools is close to the natural programming language, has its own extension file drl, and has full syntax support. Basically, the syntax drl of the natural programming language has all. Therefore, it is completely possible to write the logic of java in the drl file.

Let’s take a look at the general appearance of the drl file:

eb3ef1b0a8c1d420f113e4d786db3a2a.jpeg

drl file

It can be seen that the way Drools defines rules is a rule section, with clear when…then, indicating what to do when certain conditions are met. Pay attention to the official z number: code ape technology column, reply keywords: 1111 Get Ali’s internal Java performance optimization manual! When triggering a rule, it will automatically determine which rule should be executed. If multiple conditions are met, then can trigger multiple rules.

LiteFlow orchestration expressions are simple and easy to understand, and the bottom layer is packaged with EL expression language. It is used for the flow of components, and supports asynchronous, selection, conditional, looping, nesting and other scenarios.

The component level can not only be a java component, but also can be written in a scripting language. Currently, two scripting languages, Groovy and QLExpress, are supported. Everything that can be done in java can be done in a scripting language.

The rule file of LiteFlow roughly looks like this:

660356c338e1d06d5cebf5c86f4dca04.jpeg

LiteFlow rules file

In the above-mentioned arrangement expression of LiteFlow, the following logical flow is expressed:

0a3fccb1434a382546ab993171fcef9e.jpeg

LiteFlow orchestration expressions

LiteFlow programming expressions support THEN (synchronous), WHEN (asynchronous), SWITCH (selection), IF (condition), FOR (time loop), WHILE (conditional loop) and other large expressions, and each expression has many extended keys Words are optional.

The Groovy supported by the script component is basically similar to the Java syntax, and you can use everything supported by the Groovy language. It is even possible to additionally define classes and methods in Groovy syntax.

“Conclusion”

In general, both frameworks can use scripts to define logical fragments. At the level of defining logical fragments, Drools uses self-developed syntax, and LiteFlow uses plug-in Groovy. In fact, I personally think that Groovy is closer to Java syntax. You You can even define classes and methods in it. Drools can also use rules to define methods in advanced applications, but I think it is not so natural.

The biggest feature of LiteFlow is that in addition to defining logical fragments, it can also arrange global components. And this is why LiteFlow calls it an orchestration rule engine. Complex logical flows can be designed using simple orchestration syntax. Support java and script mixing.

Data exchange with Java

In the rules of Drools, you can use the import keyword to introduce some package classes of java for calling.

In the script component of LiteFlow, Groovy can also introduce any package of java through import to call.

In Drools, you can directly refer to the fact object.

In LiteFlow, you can directly refer to the context object, and the context context runs through the entire orchestration link.

In LiteFlow, through the @ScriptBean annotation, you can even introduce beans in the spring context and call them directly. Using this feature, you can even call rpc in the script to call the database dao object to fetch data. Although this can also be done in Drools, it is much more troublesome.

“Conclusion”

Basically, it can meet the data exchange requirements with java, but LiteFlow obviously supports more scenarios.

API and integration

At the level of API calls, Drools needs to define a series of KieContainer, KBase, and KSession objects. The LiteFlow framework only needs to use the LiteFlowExecutor object.

Drools supports programmatic access, but in springboot you need to write a lot of configuration classes to integrate.

LiteFlow not only supports programmatic access, but also provides an automatic assembly starer access method in the springboot environment. It does not even need to define LiteFlowExecutor, and the automatically assembled object can be called directly from the context.

Conclusion

The LiteFlow api is simpler and more integrated with Springboot.

Intrusive coupling comparison

Drools needs to use the KSession object to match the rules where the rules need to be used in the java code to call. Rules and java are separated. The KSession call object is coupled at the call level.

The rules of LiteFlow are also separated from Java, but LiteFlow has the concept of components, so it needs to be inherited at the component level, but it also provides the choice of declarative components, and the coupling of declarative methods is relatively reduced. At the call level, it is also necessary to call the LiteFlowExecutor object.

“Conclusion”

In terms of coupling, because LiteFlow provides orchestration features, API coupling is relatively higher. Drools is less coupled.

Learning cost of rules

The learning cost of Drools rules is quite high. Since it is a self-developed rule grammar, it requires a very comprehensive familiarization process. And the documents are all in English.

LiteFlow’s programming rules are extremely simple, and if you don’t use script components, you can basically get started in 10 minutes. Even if the groovy script is used, since groovy is very similar to java, the learning cost is very small. Moreover, there are a large number of learning materials to refer to.

The documentation of LiteFlow is complete in Chinese and English, and there is also a good Chinese community to answer questions.

Conclusion

In terms of rule learning cost, the rule learning curve of Drools is more than a little bit higher than that of LiteFlow.

Is there a language plugin

Drools has plug-ins for both Eclipse and IDEA to do syntax highlighting, pre-checking and prompting.

LiteFlow has plugins for IDEA to do highlighting, pre-checking and hinting. Not on Eclipse.

Conclusion

Considering that there are very few people using eclipse, basically the two rule engines have done it in the language plug-in.

Storage of rules

Drools rules theoretically support your rules to be stored anywhere, but all of this requires you to do it manually. Save by yourself, and get by yourself.

Drools also has a workbeanch plug-in that can store rules in the workbeanch. Only this does not require self-access.

In addition to local rules, LiteFlow natively supports storing rules in any standard SQL database, and restores native support for registration centers such as Nacos, Etcd, and zookeeper. Just configure it. In addition, an extension interface is also provided to facilitate your own expansion into any storage point.

“Conclusion”

LiteFlow’s rule storage support is much richer than that of Drools.

Can rule changes change the logic in real time

The way Drools hot-refresh rules now looks a bit silly, its rules are generated by jar. Then the system remotely and dynamically reads the jar package to complete the rule refresh.

And the hot change of the rules must be carried out through the workbench.

LiteFlow is much more advanced at this level. If you use Nacos, Etcd, zookeeper, etc. to store, you don’t need to do anything, and the changes will be automatically refreshed. If you are SQL database storage, or local storage. After changing the rules, you need to call an API provided by the LiteFlow framework to perform hot changes. Both methods can be hot updated. And it is smooth under high concurrency.

“Conclusion”

LiteFlow is much more advanced than Drools in hot update design.

Whether there is an interface form to support

Drools has workbench, which is an independent plug-in package that provides web interface writing rules and fact objects. And provides the ability to check and deploy. But because Drools is mainly concerned with logic fragments, it does not need to provide drag-and-drop UI functions at the layout level, but only provides the ability to write rules on the interface.

LiteFlow does not have an interface shape. At present, only the interfaces provided by the third-party Nacos and Etcd can be used to assist in the modification of the interface rules.

“Conclusion”

Drools is ahead of LiteFlow in terms of UI form ecology.

Framework performance

The same logic Demo is implemented here with Drools and LiteFlow.

A demo case of adding points based on the order amount.

The case logic is very simple, dynamically judge how many points should be added according to the amount of the order:

Less than 100 yuan, no points.

100 to 500 yuan, plus 100 points.

500 to 1000 yuan, plus 500 points.

More than 1,000 yuan, plus 1,000 points.

The rules of Drools are as follows:

package rules;

import com.example.droolsdemo.entity.Order;

rule "score_1"
when
    $order:Order(amount<100)
then
    $order.setScore(0);
    System.out.println("triggered rule 1");
end

rule "score_2"
when
    $order:Order(amount>=100 & amp; & amp; amount < 500)
then
    $order.setScore(100);
    System.out.println("triggered rule 2");
end

rule "score_3"
when
    $order:Order(amount>=500 & amp; & amp; amount < 1000)
then
    $order.setScore(500);
    System.out.println("triggered rule 3");
end

rule "score_4"
when
    $order:Order(amount>=1000)
then
    $order.setScore(1000);
    System.out.println("triggered rule 4");
end

The equivalent LiteFlow rules are as follows:

<?xml version="1.0" encoding="UTF-8"?>
<flow>
    <nodes>
        <node id="w" type="switch_script">
            <![CDATA[
                def amount = defaultContext.getData("order").getAmount();

                if (amount < 100){
                    return "a";
                }else if(amount >= 100 & amp; & amp; amount < 500){
                    return "b";
                }else if(amount >= 500 & amp; & amp; amount < 1000){
                    return "c";
                }else{
                    return "d";
                }
            ]]>
        </node>

        <node id="a" type="script">
            <![CDATA[
                def order = defaultContext.getData("order");
                order.setScore(0);
                println("execute rule a");
            ]]>
        </node>

        <node id="b" type="script">
            <![CDATA[
                def order = defaultContext.getData("order");
                order.setScore(100);
                println("execute rule b");
            ]]>
        </node>

        <node id="c" type="script">
            <![CDATA[
                def order = defaultContext.getData("order");
                order.setScore(500);
                println("execution rule c");
            ]]>
        </node>

        <node id="d" type="script">
            <![CDATA[
                def order = defaultContext.getData("order");
                order.setScore(1000);
                println("execution rule d");
            ]]>
        </node>
    </nodes>

    <chain name="chain1">
        SWITCH(w).TO(a, b, c, d);
    </chain>
</flow>

When the two frameworks are all written in scripts, during the test, remove all the print logs and execute them 10w times. The results are as follows:

Drools executes 100,000 times and takes 0.7 seconds

The LiteFlow full script component executes 100,000 times and takes 3.6 seconds

Since LiteFlow needs to execute scripts and orchestrate scripts in the case of full script components, it takes longer.

If LiteFlow replaces the component with java and executes it again, the result is as follows:

LiteFlow all Java components are executed 100,000 times, and it takes 0.5 seconds

Conclusion

If LiteFlow runs in full script mode, it will take longer than Drools. If it runs with all java components, its performance can surpass Drools a little.

So for LiteFlow, if you want higher performance, use java components, and if you want higher flexibility, use script components.

In fact, in actual business, it is more recommended to extract the logic that is easy to change and write it as a script component, and use java + script mixed compilation.

Conclusion

Why do you use Drools as a comparison? First, in the subject’s mind, Drools has always been the benchmark in the rule engine industry. Drools has many concepts that are worth learning. The second is also because the subject is only familiar with Drools, and other frameworks have not been used well.

But on the whole, as a rising star of the domestic rule engine, LiteFlow is obviously better than Drools in terms of design concept and support. As a new direction of the rule engine, the orchestration rule engine will continue to be explored. I hope everyone can support this domestic rule engine. In the direction of programming, LiteFlow has many other exploratory gameplay and advanced features in addition to some of the features mentioned in the article. It is a framework worth digging into.

Welcome to join my knowledge planet, discuss architecture and exchange source code together. How to join, Long press the QR code below:

423302b6dec051f79feb29104ca3efe2.png

The source code has been updated on Knowledge Planet and the analysis is as follows:

e0e669d4247d2f68f22a23e843854cd6.jpeg

8f269ab59cc416b012fab454f08ba42c.jpeg

783c646405d1da1b3a5d35e89b8c65f2.jpeg

308fa40e7cb5a5306f62fb2e9ff2582a.jpeg

The recently updated series “Introduction to Taro SpringBoot 2.X” has more than 101 articles, covering MyBatis, Redis, MongoDB, ES, sub-database and sub-table, read-write separation, SpringMVC, Webflux, permissions, WebSocket, Dubbo, RabbitMQ, RocketMQ , Kafka, performance testing, etc.

Provides a SpringBoot example with nearly 3W lines of code, and an e-commerce microservice project with more than 4W lines of code.

How to get it: Click “Looking“, follow the official account and reply to 666 to receive, more content will be provided one after another.

If the article is helpful, please read it and forward it.
Thank you for your support (*^__^*)