background

When it comes to the four words of rule engine, we must have heard more or less in work or various articles, but many students are often scared by the two words of engine, thinking that this is what black technology. Recently, I have been investigating the rule engine. Here, I will introduce to you what a rule engine is.

Why do you need a rules engine

The benefits of a rule engine are many, and here we will analyze them from different perspectives.

From the developer’s perspective

In the era of no rule engine, some businesses with complicated logic have to add if-else to meet our complex business scenario. This is fine for developers, but for those who take over from them, as soon as they see if-else everywhere, those who have experienced it will know. Of course, if-else can be optimized through some modes. For example, using the policy pattern, or using some annotations to optimize the extension point, can solve some of the code is not clear, but it still does not solve the problem of slow development, need to go online, etc. For example, in the risk control system, because the logic of risk control is constantly changing, if we write death in the code, then a change will change the code, the last offline, this is obviously unacceptable to us. So we need a rules engine to change this, to make these business rule changes in an efficient and reliable way.

From the perspective of a business person

In the previous development mode, business personnel proposed business rules and asked developers to make corresponding business development. Whether the final business rules developed are consistent with those proposed by business personnel needs to be verified through a large number of tests. And our developers’ understanding of the business is easily different from the business people’s proposed business, which leads to higher development costs. With a rules engine, we can make the following improvements:

  • The business people configure the business rules independently, and the developers do not need to understand them, so that the business people’s rules are consistent with the real situation.
  • Increase the transparency of business, business personnel after the configuration of other business personnel can also know, before only through the code QQ.
  • Rules are effectively changed and put on line. General business personnel hope to put on line as soon as possible after they put forward requirements, but they need to have code development, project launch and other links before, and now they are ready to use after the business personnel are configured.
  • Reduce the contradiction between business people and developers, developers often because some of the time factor or some understanding does not reach the designated position lead to the rules of business personnel implementation deviation, the last business society to develop students produce some small contradiction, this is completely remove business configuration after the opened, as long as constantly upgrade rules engine, business rules will no longer is dependent on for developers.

What is a rules engine

Now, with all of these benefits, many of you may be wondering, what does a rule engine look like? Generally speaking, it falls into the following three categories:

  • Low configuration: No configuration interface, the business person writes the engine rules DSL, which is generally stored in a database or file. This does not completely free the coupling between the business person and the developer, but it speeds up the rollout of the business code and makes rule changes easier.
  • Premium: the general is a particular system, we set up some for this system targeted page, such as the following screenshot is a certain risk control system, risk control system of the rule engine is relatively simple, you just need to determine whether certain parameters conform to certain conditions, and then returns the value of a fixed.

  • Full version: In the advanced version, the rules engine is just one component, which is generally difficult to replicate for other scenarios. A full version of the rules engine, however, is intended to be extremely versatile. Here is a screenshot from a commercial rules engine:

As you can see, there are many expressions of rule engines: decision sets, decision tables, decision trees, etc., which are suitable for many places where we need to use rule engines. The following is a temporary configuration of decision trees, which is similar to the configuration of risk control above, but more general.

Now that you have a basic idea of what a rule engine is, let’s talk about some open source rule engines.

Which rule engines are available

There are many open source rule engines in the community, indicating that different business teams and companies are interested in this. However, on the whole, the major categories are divided into the following categories:

  • Mature rules engine through interface configuration: This rule engine is relatively heavy, but because of its full functionality, some businesses will choose this one, commonly known as Drools,urule.
  • Based on JVM scripting language: In fact, this is not a mature rule engine, it should be the core technology of the rule engine. Many companies, such as Meituan, will think drools is too heavy, and then they will develop a lightweight rule engine based on some JVM scripting languages. Some of the famous ones here are: Groovy, aviator, qlexpress.
  • Rule engine based on Java code: the above is based on the JVM scripting language to do, there will be some cost of grammar learning, so there is a rule engine based on Java code to do, such as through some annotations to achieve abstract way to do the extension of rules, the more famous is: easyRules.

Mature rules engine

As a full version of the mature rules engine, often can be sold as sass products, Urule open source part at the same time, but also sell their own advanced features, Drools is a pure open source product, if you want to experience this rule engine can directly go to urule.bstek.com/ to experience his products, do not need…

How does being a full version satisfy all kinds of weird rules? Within each of these rule engines there are several rule designers to satisfy your desired rule scenario:

  • Rule set: a set of rules composed of common rules and circular rules. It is the most frequently used way of implementing business rules. Generally divided into wizard: through the graphical interface composition; There’s also scripting: through a custom DSL language, similar to the JVM scripting rules engine we’ll look at below.

This is our wizard rule set, and our rule set is a good choice for if/else/and/or and while loop logic. To write it in a DSL, there are some rules to follow. Here is the Drools DSL:

Overall syntax and we Java is quite different, there is a certain cost of learning.

  • Decision table: If our business rules are in the form of a table, we can use the decision table to calculate the rules. Usually our product or operations staff will give you an Excel table to execute the rules, as shown in the figure below:

If we wanted to do this with a rule set, that would be fine, but the overall complexity would require a lot of if/else writing, so we can just use our decision table to do what we need:

  • Scorecards: If you need to score entities collectively, you can use scorecards to do so. For example, to assess a person’s cholesterol risk:

  • The decision tree: Decision tree and others are a little different, such as the decision rules important to control the high risk we want to see the user registration, if through the set of rules to see we need to find all the rule sets, decision tree is different, but the rules are at the bottom, the results are at the top, the decision tree to express the business more image, we can according to their own business to the designer to select the appropriate rules. Here is an ordinary decision tree:

  • Rule flow: Rule flow is also called decision flow. Its entire structure is similar to workflow. It is used to arrange the execution order of existing decision set, decision table, cross decision table, decision tree, score card, complex score card or other decision flow, so as to realize a large and complex business rule clearly and intuitively. The process of orchestration can be executed in serial, parallel, or conditionally selected branches.

With these different rule designers, we can design our different rule scenarios, so how we should call these rules, generally speaking, the following three ways are provided:

  • Generate JAR package: The jar package will be generated after the configuration is completed, and then we will introduce it into our project. The project will call this jar package.
  • Hot update mode: The rules engine helps you hot update this JAR file, dynamically loading it into our JVM memory, this way does not require a restart of the machine.
  • Service pattern: The rules engine provides its own machine and then calculates the rules through remote calls.

You can choose the appropriate invocation pattern for your scenario.

Pete algorithm

Both Drools and Urule chose the Rete algorithm for rule matching. Rete is an efficient method to compare a large number of pattern sets and a large number of object sets. All the objects and rules matching each pattern are found through network filtering. Its basic principle is to achieve the acceleration of rule matching by space changing time. Those of you who are interested can come down and search.

Rules engine for the JVM scripting language

Drools will enter into the selection when the Internet company carries out the rule engine research, but it often fails to be selected due to the heavy weight and high learning cost. Often this lightweight scripting language is favored by Internet companies. Generally speaking, there are three scripting languages that are more commonly used for rules engines:

  • Groovy:Groovy is a SCRIPTING language maintained by the Apache Foundation. It is a JVM-based language that combines many powerful features of Python, Ruby, and Smalltalk. Groovy code works well with Java code and can be used to extend existing code. Because it runs on the JVM, Groovy can also use libraries written in other non-Java languages. The open source risk control engine Radar is implemented using Groovy.
  • Aviator: Aviator, also known as AviatorScript, is a high-performance, lightweight scripting language that resides on the JVM. Also known as expression language, provides a limited syntax, functions are first-class citizens like JS, supports closures and functional programming. The main thing is that it is a project of Google open source, and its quality is very guaranteed. In meituan, aviator, a lightweight language, is selected as the rule engine for most scenarios that use the rule engine, such as risk control and data rules.
  • Qlexpress: Qlexpress is a scripting language developed by Ali. It is used in Ali and some Java companies, but I don’t recommend it, because the community activity of this is really low. The last update was more than a year ago.

So how do we choose between the three JVM scripting languages? I recommend aviator. Unlike the other two languages, Aviator only provides limited syntax, unlike Groovy, which is a complete language. For example, you can do some dangerous operations, and if you enter system.exit (0), you can directly exit our process. Aviator didn’t even support if/else loops when it started. It only supported them in the latest version 5.0, so the overall functionality it provides is a safe sandbox.

Aviator’s basic process of translating expressions directly into Java bytecode execution takes up to two trips (one when execution first is enabled and one when compilation first is enabled), which ensures that it performs better than most interpreted expression engines. Tests have shown this to be the case. Second, it doesn’t rely on any third party libraries other than commons-Beanutils (for reflection), so it’s very lightweight, with the size of the entire JAR at 430K even at the current 5.0 version.

Back to the above risk control rule engine, what should we do in aviator if we want to implement the rule that the order amount is more than 100 yuan and the user belongs to VIP?

Public static void main(String[] args) {// First construct parameters Map<String, Object> env = new HashMap<String, Object>(); env.put("orderAmount", 101); env.put("vip", true); Boolean result = (Boolean) aviatoreValuator. execute("orderAmount > 100 && VIP ", env); System.out.println(result); } // Output trueCopy the code

As you can see, we first construct the two attributes of whether the user is VIP and the orderAmount, and then just define the expression orderAmount > 100 && VIP to get the result we want. Therefore, as long as operators or products think of different rules, we can immediately configure, we can save this rule in the database, and then read and execute. For the interface needs to cooperate with the front end, so that some front-end controls can be automatically converted into this expression language, you can complete automation.

Although aviator is different from Java language, but its overall cost is relatively low, for the Aviator syntax interested can see the document 5.0: www.yuque.com/boyan-avfmj…

Rules engine for Java code

Java-based code rules engines tend to be a framework, and we implement them based on the conditions that the framework defines. Let’s take an example: If we have multiple processes to add numbers, for example, we add the prefix “tutor” for ape, we add the prefix “Conan” for zebra, and we add the prefix “solar” for question searching, how would we write it?

If (biz == "tutor"){tradeNo = "tutor" + tradeNo; }else if(biz == "zebra "){tradeNo = "conan" + tradeNo; }else if (biz == "search "){tradeNo = "solar" + tradeNo; }Copy the code

If /else, it doesn’t look like it’s going to be so bad, but it breaks the open closed principle, because if you’re adding logic or changing logic, you’re going to have to change this piece of code, and if you make a mistake and it affects the rest of the logic it’s not worth it. So how do we do this with easyRule?

@Rule(priority = 1) public class FudaoRule { @Condition public boolean isFudao(@Fact("biz") String biz) { return biz == "Ape tutoring "; } @Action public void process(Facts facts) { String tradeNo = facts.get("tradeNo"); facts.put("tradeNo", "tutor" + tradeNo); } } @Rule(priority = 2) public class BanmaRule { @Condition public boolean isBanma(@Fact("biz") String biz) { return biz == "; } @Action public void process(Facts facts) { String tradeNo = facts.get("tradeNo"); facts.put("tradeNo", "conan" + tradeNo); }}Copy the code

We implement these two different classes. The @rule annotation defines priority as our if/else priority, @condition as our Condition, and @Action as our Action after matching. In this way, if we add or modify the logic later, we can change it in different classes, which satisfies our open closed principle.

EasyRules also supports the use of YAML files to define rules, similar to our previous DSL, but I think the way to implement Java class annotations is its big feature, many students if they just want to choose some Java extension framework its design idea is a worthy reference, worthy of learning framework.

The last

With the rise of the Internet platform and the middle Platform, the rule engine gradually appears in everyone’s view. If you’re in a flexible business, if you’re still stuck with if/else logic, if your product or operations people are always making fun of your development for not meeting their needs, then choose a good rule engine to solve these problems. Finally, if you have anything to communicate with me about the rule engine, you can follow my public number and get in touch with me.

If you think this article is helpful to you, your attention and retweet are my greatest support, O(∩_∩)O: