当前位置:网站首页>2 first experience of drools
2 first experience of drools
2022-06-13 05:35:00 【dream21st】
1 Drools First experience
This section uses an example to experience Drools Rule engine writing . Now let's suppose we have a scenario like this : There is a loan scorecard system , According to some basic conditions of customers ( Age 、 Gender 、 Years of service 、 Monthly income and unit nature, etc ) To give the customer a score , The amount of the final customer is also affected by this score .
1.1 Build the project
Create a simple maven project , project pom.xml Rely on the jar Package coordinates are as follows :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>drools-demo</artifactId>
<groupId>com.dream21th</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>drools-first</artifactId>
<dependencies>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-compiler</artifactId>
<version>7.6.0.Final</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>1.2 Case description
Now suppose there is such a requirement : If the customer's age is 18 One year old to 60 One year old , Customer score plus 20, In other cases, scores will not be counted ; If the customer's monthly income is 30000 And above plus 20 branch , The monthly income is in 10000 To 30000 Intercalation 10 branch , The monthly income is in 5000 To 10000 Intercalation 5 branch , lower than 5000 Regardless of the score ; If the client is a state-owned enterprise plus 10 branch , Private enterprise plus 8 branch , Foreign enterprises add 5 branch , Other plans 3 branch .
See the above requirements , The most intuitive feeling is , Write a few if else The branch can be done , In fact, for this example , It is implemented by hard coding , It's very simple , But we've talked about , If one day the demand changes , Need to increase the length of service score , Or add the gender type of the enterprise . What to do in case of requirements change ? If you use hard coding, you can only change the code to test and go online .
1.3 Code implementation
The following uses Drools Rule engine , First, write a business class code to put related attribute parameters , The meanings and code values of related attributes have been explained in the notes .
package com.dream21th.first;
import java.math.BigDecimal;
public class PersonBasicInfo {
/**
* full name
*/
private String name;
/**
* Age
*/
private Integer age;
/**
* Gender 1: male 2: Woman 0: Unknown
*/
private String gender;
/**
* Monthly income
*/
private BigDecimal monthIn;
/**
* Working years
*/
private Integer workAge;
/**
* Unit nature 1: State-owned enterprises 2, Private enterprise 3, foreign 4, other
*/
private String companyType;
/**
* The final score
*/
private Integer score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public BigDecimal getMonthIn() {
return monthIn;
}
public void setMonthIn(BigDecimal monthIn) {
this.monthIn = monthIn;
}
public Integer getWorkAge() {
return workAge;
}
public void setWorkAge(Integer workAge) {
this.workAge = workAge;
}
public String getCompanyType() {
return companyType;
}
public void setCompanyType(String companyType) {
this.companyType = companyType;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
}
Then write according to the above rules Drools Rules file , There is no detailed description here , The specific rules are as follows , The role of each rule is described in the comments :
package ruls;
import com.dream21th.first.PersonBasicInfo
import java.util.Objects;
import java.math.BigDecimal;
/**
* This rule is to judge age , If the age is 18 To 60 Between , Score plus 20
**/
rule "rule_age"
when
$s:PersonBasicInfo(age>18 && age<60)
then
Integer score=Objects.isNull($s.getScore())?0+20:$s.getScore()+20;
$s.setScore(score);
end
/**
* The following three are the monthly income rules , The income of the current month is greater than 30000 Add 20 branch , stay 10000 To 30000 Intercalation 10 branch , stay 5000 To 10000 Intercalation 5 branch , lower than 5000 No bonus points
**/
rule "rule_monthIn_0"
when
$s:PersonBasicInfo(monthIn.compareTo(BigDecimal.valueOf(30000))>=0)
then
Integer score=Objects.isNull($s.getScore())?0+20:$s.getScore()+20;
$s.setScore(score);
end
rule "rule_monthIn_1"
when
$s:PersonBasicInfo(monthIn.compareTo(BigDecimal.valueOf(30000))<0 && monthIn.compareTo(BigDecimal.valueOf(10000))>=0)
then
Integer score=Objects.isNull($s.getScore())?0+10:$s.getScore()+10;
$s.setScore(score);
end
rule "rule_monthIn_2"
when
$s:PersonBasicInfo(monthIn.compareTo(BigDecimal.valueOf(10000))<0 && monthIn.compareTo(BigDecimal.valueOf(5000))>=0)
then
Integer score=Objects.isNull($s.getScore())?0+5:$s.getScore()+5;
$s.setScore(score);
end
/**
* The following are the rules of enterprise nature : If it is 1 State-owned enterprises Add 10
* 2 Private enterprise Add 8
* 3 foreign enterprise Add 5
* 4 other Add 3
**/
rule "rule_companyType_0"
when
$s:PersonBasicInfo(companyType=='1')
then
Integer score=Objects.isNull($s.getScore())?0+10:$s.getScore()+10;
$s.setScore(score);
end
rule "rule_companyType_1"
when
$s:PersonBasicInfo(companyType=='2')
then
Integer score=Objects.isNull($s.getScore())?0+8:$s.getScore()+8;
$s.setScore(score);
end
rule "rule_companyType_2"
when
$s:PersonBasicInfo(companyType=='3')
then
Integer score=Objects.isNull($s.getScore())?0+5:$s.getScore()+5;
$s.setScore(score);
end
rule "rule_companyType_3"
when
$s:PersonBasicInfo(companyType=='4')
then
Integer score=Objects.isNull($s.getScore())?0+3:$s.getScore()+3;
$s.setScore(score);
endBecause of the simple maven project , It also needs to be in the resource directory (resources) Let's create a directory META-INF, And create a new file under this directory kmodule.xml, The contents of the document are as follows , This file provides a default for the project kie:
<?xml version="1.0" encoding="UTF-8" ?>
<kmodule xmlns="http://www.drools.org/xsd/kmodule">
<!--
name: Used to specify kbase The name of , You can specify any , But need only
packages: Specify the directory of the rule file ( stay resources Below directory ), Fill in... According to the actual situation , Otherwise, it cannot be loaded into the rule file
default: Specify the current kbase Is it the default
-->
<kbase name="myFirst" packages="first" default="true">
<!--
name: Appoint ksession name , You can do whatever you want , But need only
default: Specify the current session Is it the default
-->
<ksession name="ksession-first" default="true"/>
</kbase>
</kmodule>The last step , Create a test case , Write test code :
package com.dream21th.first;
import org.junit.Test;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import java.math.BigDecimal;
/*
* @Author dream21th
**/
public class DroolsFirstTest {
@Test
public void test1(){
KieServices kieServices = KieServices.Factory.get();
KieContainer kieClasspathContainer =kieServices.getKieClasspathContainer();
// Conversation object , Used to interact with the rule engine
KieSession kieSession = kieClasspathContainer.newKieSession();
PersonBasicInfo personBasicInfo=new PersonBasicInfo();
personBasicInfo.setName(" zhaoyun ");
personBasicInfo.setAge(34);
personBasicInfo.setMonthIn(new BigDecimal(100000));
personBasicInfo.setCompanyType("3");
kieSession.insert(personBasicInfo);
// Activate rule engine , If the rule match is successful, execute the rule
kieSession.fireAllRules();
System.out.println(String.format(" Name of customer :【%s】 The final score :【%s】",personBasicInfo.getName(),personBasicInfo.getScore()));
// Close session
kieSession.dispose();
}
}The age in the example is 34 meter 20 branch , Monthly income 100000 meter 20 branch , Unit nature 3 meter 5 branch , In the end, the total score should be calculated 45 branch , The result of running the code is as follows , The results meet expectations :

The hierarchy of the whole project is as follows :
边栏推荐
- Metaltc4.0 stable release
- Time display of the 12th Blue Bridge Cup
- MySQL main query and sub query
- August 15, 2021 another week
- Information collection for network security (2)
- Top slide immersive dialog
- Flex布局自适应失效的问题
- Some methods of string
- The problem of flex layout adaptive failure
- Case - simulated landlords (upgraded version)
猜你喜欢

Django uploads local binaries to the database filefield field

10 signalstartevent and signalcatchingevent of flowable signal events

powershell优化之一:提示符美化

List collection concurrent modification exception

Quartz database storage

Case - recursive factorial (recursive)

ZABBIX wechat alarm

SQL table columns and statements of database

About anonymous inner classes

16 the usertask of a flowable task includes task assignment, multi person countersignature, and dynamic forms
随机推荐
Deleted the jupyter notebook in the jupyter interface by mistake
How to set the import / export template to global text format according to the framework = (solve the problem of scientific counting)
Understanding inode
powershell优化之一:提示符美化
Three paradigms of MySQL
17.6 unique_lock详解
Summary of the 11th week of sophomore year
Case - recursive factorial (recursive)
Problems encountered in the use of PgSQL
Initial redis experience
Compilation croisée helloworld avec cmake
Std:: map insert details
16 the usertask of a flowable task includes task assignment, multi person countersignature, and dynamic forms
Create a harbor image library from the command line
mongo
使用cmake交叉編譯helloworld
About the solution of pychart that cannot be opened by double clicking
Set the correct width and height of the custom dialog
Luogu p3654 fisrt step
Redis plus instructions