What is the use of the rule engine in those real-world scenarios? Think about a problem like applying for a credit card. Everyone will go through a check when they apply for a credit card. This check process can actually be regarded as checking whether your information conforms to the rules. Only those who conform to the rules can apply for a credit card.
Remember the infinite nesting of if else s you wrote before, you can actually use the rule engine instead, to decouple the code and make the program flexible.
Catalog
Advantages of using the rule engine
Introduction to Drools Rule Engine
What is the Rule Engine
The Rule Engine, fully known as the Business Rule Management System, is called BRMS (Business Rule Management System) in English. The main idea of the Rule Engine is to separate the business decision parts of an application and write business decisions (business rules) using predefined semantic modules that can be configured and managed by users or developers when needed.
It is important to note that the rule engine is not a specific technical framework, but rather a system, the business rule management system. At present, there are specific rule engine products on the market: drools, VisualRules, iLog and so on.
The rule engine separates business decisions from application code, receives data inputs, interprets business rules, and makes business decisions based on business rules. The rule engine is actually an input-output platform.
When a rule engine is introduced into the system, business rules no longer reside in the system as program code, but instead are the rule engine that processes the rules, which are stored in the rule base and are completely program independent. Business people can manage business rules like managing data, such as querying, adding, updating, statistics, submitting business rules, and so on. Business rules are loaded into the rule engine to supply system calls.
Advantages of using the rule engine
The advantages of using the rule engine are as follows:
1. Separate business rules from system code to centralize the management of business rules
2. Business rules can be extended and maintained at any time without restarting services
3. Business rules can be dynamically modified to respond quickly to changes in demand
4. The rule engine is relatively independent and only concerned with business rules, which enables business analysts to participate in editing and maintaining the system's business rules.
5. Reduce the cost and risk of hard-coded business rules
6. Use the rule editing tools provided by the rule engine to make complex business rule implementations simple
Rule Engine Scenario
For systems with more complex business rules and frequent changes in business rules, the rule engine is appropriate as follows:
1. Risk Control System - Risk Loan, Risk Assessment
2. Anti-fraud Project - Bank Loan, Credit Verification
3. Decision Platform System - Financial Computing
4. Promotion Platform System - Full Reduction, Discount, Markup Purchase
Introduction to Drools Rule Engine
drools is an open source rule engine developed in the Java language by the JBoss organization that frees complex and variable business rules from hard coding and stores them as rule scripts in files or specific storage media, such as databases, so that changes to business rules do not require modifications to project codes. Restarting the server will take effect immediately in the online environment.
drools website address: https://drools.org/
drools source download address: https://github.com/kiegroup/drools
When drools are used in a project, they can be used individually or integrated with spring. If you use it alone, you only need to import the following maven coordinates:
<drools.version>7.5.0.Final</drools.version> <!--drools--> <dependency> <groupId>org.drools</groupId> <artifactId>drools-core</artifactId> <version>${drools.version}</version> </dependency> <dependency> <groupId>org.drools</groupId> <artifactId>drools-compiler</artifactId> <version>${drools.version}</version> </dependency> <!-- decision tables --> <dependency> <groupId>org.drools</groupId> <artifactId>drools-decisiontables</artifactId> <version>${drools.version}</version> </dependency> <!-- Template --> <dependency> <groupId>org.drools</groupId> <artifactId>drools-templates</artifactId> <version>${drools.version}</version> </dependency> <dependency> <groupId>org.kie</groupId> <artifactId>kie-spring</artifactId> <version>${drools.version}</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </exclusion> </exclusions> </dependency>
Drools Rules Major Components
In general, writing a Drools file is an essential part of:
package
rule
when
LHS
then
RHS
end
drools API development steps
drools first demo
1:Create a drools profile
Create kmodule under META-INF in the resources directory. XML file
<?xml version="1.0" encoding="UTF-8" ?> <kmodule xmlns="http://www.drools.org/xsd/kmodule"> <!-- name:Appoint kbase The name can be arbitrary, but needs to be unique packages:Specify the directory of the rule file, which needs to be filled in as appropriate, otherwise it cannot be loaded into the rule file default:Specify the current kbase Is Default --> <kbase name="myKbase1" packages="rule" default="true"> <!-- name:Appoint ksession Name, can be any, but needs to be unique default:Specify the current session Is Default --> <ksession name="ksession-rule" default="true"/> </kbase> </kmodule>
2: Create rules
Create drools rule files in the rule directory under the resources directory
//Book preferential rules package book.discount import com.fairyland.demo.pojo.Order //Rule 1: There is no discount for the total price of books purchased under 100 yuan rule "book_discount_1" when $order:Order(originalPrice < 100) then $order.setRealPrice($order.getOriginalPrice()); System.out.println("Successfully matched Rule 1: No discount for the total book price below 100 yuan"); end //Rule 2: A discount of 20 yuan for the total price of the book purchased between 100 and 200 yuan rule "book_discount_2" when $order:Order(originalPrice < 200 && originalPrice >= 100) then $order.setRealPrice($order.getOriginalPrice() - 20); System.out.println("Successfully matched Rule 2: A discount of 20 yuan for the total price of the book purchased between 100 and 200 yuan"); end //Rule 3: 50 yuan discount for the total price of books purchased from 200 to 300 yuan rule "book_discount_3" when $order:Order(originalPrice <= 300 && originalPrice >= 200) then $order.setRealPrice($order.getOriginalPrice() - 50); System.out.println("Successfully matched Rule 3: 50 yuan discount for the total price of the book purchased between 200 and 300 yuan"); end //Rule 4: 100 yuan discount for the total price of books purchased above 300 yuan rule "book_discount_4" when $order:Order(originalPrice >= 300) then $order.setRealPrice($order.getOriginalPrice() - 100); System.out.println("Successfully matched to Rule 4: 100 yuan discount for the total price of the book purchased above 300 yuan"); end
3: Create Order entity class
public class Order { //Original order price, i.e. pre-discount price private Double originalPrice; //Real price of the order, i.e. post-discount price private Double realPrice; public String toString() { return "Order{" + "originalPrice=" + originalPrice + ", realPrice=" + realPrice + '}'; } public Double getOriginalPrice() { return originalPrice; } public void setOriginalPrice(Double originalPrice) { this.originalPrice = originalPrice; } public Double getRealPrice() { return realPrice; } public void setRealPrice(Double realPrice) { this.realPrice = realPrice; } }
4: Testing
public static void testOrder() { KieServices kieServices = KieServices.Factory.get(); KieContainer kieClasspathContainer = kieServices.getKieClasspathContainer(); //Session object for interacting with the rule engine KieSession kieSession = kieClasspathContainer.newKieSession(); //Construct the order object, set the original price, and let the rule engine calculate the price after the discount according to the discount rules Order order = new Order(); order.setOriginalPrice(210D); //Provide data to the rule engine, which matches rules based on the data provided kieSession.insert(order); //Activate the rule engine and execute the rule if the rule matches successfully kieSession.fireAllRules(); //Close Session kieSession.dispose(); System.out.println("Price before offer:" + order.getOriginalPrice() + ",Price after discount:" + order.getRealPrice()); }
The example above is a rule file that needs to be customized. This does not satisfy the rule file and code decoupling that we are talking about, because some code is also needed inside the rule file, and the configuration file cannot be loaded automatically.
Rule Engine Composition
The drools rule engine consists of three parts:
Working Memory
Rule Base
Inference Engine
Inference Engine includes:
Pattern Matcher
Agenda
Execution Engine
Explanation of related concepts
Working Memory: Working memory, the drools rule engine retrieves data from the Working Memory and matches the rules defined in the rules file with the pattern, so the application we develop just needs to insert our data into the Working Memory, for example, in this case we call kieSession.insert(order) inserts the order object into working memory.
Fact: The fact that in the drools rule application, the object after inserting a common JavaBean into Working Memory is a Fact object, for example, the Order object in this case is a Fact object. Fact objects are bridges or channels through which our application and rule engines interact with data.
Rule Base: The rule base, the rules that we define in the rule file, are loaded into the rule base.
Pattern Matcher: A matcher that matches all the rules in Rule Base to the Fact object in Working Memory, and the rules that match successfully are activated and put into Agenda.
Agenda: An agenda for rules that are activated after pattern matching through a matcher.
Execution Engine: Execution engine that executes the rules activated in Agenda.
Rule Engine Execution Process
Introduction to KIE
The API s we often use when working with Drools and the relationships between them are as follows:
As you can see from the core API above, most of the class names start with Kie. Kie is all known as Knowledge Is Everything, short for "knowledge is everything", and is the general name of a series of Jbox projects. As illustrated below, Kie's main modules are OptaPlanner, Drools, UberFire, and jBPM. (
From the figure above, you can see that Drools is a component of the entire KIE project, and Drools also includes a Drools-WB module, which is a visual rule editor.