当前位置:网站首页>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);
end
Because 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 :
边栏推荐
- Database design
- Basic operations of MySQL auto correlation query
- Standard input dialog for pyqt5 qinputdialog
- Dynamic and static libraries
- Error: unmapped character encoding GBK
- Pychart professional edition's solution to SQL script error reporting
- RT thread console device initialization
- About Evaluation Metrics
- Information collection for network security (2)
- Unity游戏优化(第2版)学习记录7
猜你喜欢
priority inversion problem
Django uploads local binaries to the database filefield field
Difference between deviation and variance in deep learning
Dup2 use
Three paradigms of MySQL
Float type value range
Metartc4.0 integrated ffmpeg compilation
powershell优化之一:提示符美化
890. Find and Replace Pattern
Case - the list set stores student objects and traverses them in three ways
随机推荐
Course outline of market drawing 1- basic knowledge
metaRTC4.0稳定版发布
11 signalthrowingevent and signalboundaryevent of flowable signal event
Case - the list set stores student objects and traverses them in three ways
Web site learning and sorting
Pyqt5 controls qpixmap, qlineedit qsplitter, qcombobox
Initial redis experience
Set the correct width and height of the custom dialog
【多线程编程】Future接口获取线程执行结果数据
C calls the API and parses the returned JSON string
Case - count the number of occurrences of each string in the string
How to Algorithm Evaluation Methods
Problems encountered in the use of PgSQL
The 13th week of the second semester of sophomore year
MySQL table data modification
Introduction to R language 4--- R language process control
Quartz database storage
Time display of the 12th Blue Bridge Cup
MySQL log management and master-slave replication
Pychart encountered time zone problem when connecting to MySQL timezone