当前位置:网站首页>Simple use of drools decision table
Simple use of drools decision table
2022-07-02 12:14:00 【huan_ one thousand nine hundred and ninety-three】
List of articles
- One 、 background
- Two 、 A simple decision table
- 3、 ... and 、 demand
- Four 、 Realization
- 5、 ... and 、 Complete code
- 6、 ... and 、 Reference documents
One 、 background
In the previous post , Our business rules are written in drl In file , This is no problem for developers , Business people are not very friendly , Let's briefly learn about this article drools Use of decision tables in , The rule is written in excel In file .
Two 、 A simple decision table

In the picture above ResultSet and ResultTable Is a must , And in the same bag , We'd better upload only one decision table .
1、 Process multiple in the same decision table Sheet page

2、RuleSet What properties can be found below
| Label | Value | Usage |
|---|---|---|
RuleSet | The package name for the generated DRL file. Optional, the default is rule_table. | Must be the first entry. |
Sequential | true or false. If true, then salience is used to ensure that rules fire from the top down. | Optional, at most once. If omitted, no firing order is imposed. |
SequentialMaxPriority | Integer numeric value | Optional, at most once. In sequential mode, this option is used to set the start value of the salience. If omitted, the default value is 65535. |
SequentialMinPriority | Integer numeric value | Optional, at most once. In sequential mode, this option is used to check if this minimum salience value is not violated. If omitted, the default value is 0. |
EscapeQuotes | true or false. If true, then quotation marks are escaped so that they appear literally in the DRL. | Optional, at most once. If omitted, quotation marks are escaped. |
IgnoreNumericFormat | true or false. If true, then the format for numeric values is ignored, for example, percent and currency. | Optional, at most once. If omitted, DRL takes formatted values. |
Import | A comma-separated list of Java classes to import from another package. | Optional, may be used repeatedly. |
Variables | Declarations of DRL globals (a type followed by a variable name). Multiple global definitions must be separated by commas. | Optional, may be used repeatedly. |
Functions | One or more function definitions, according to DRL syntax. | Optional, may be used repeatedly. |
Queries | One or more query definitions, according to DRL syntax. | Optional, may be used repeatedly. |
Declare | One or more declarative types, according to DRL syntax. | Optional, may be used repeatedly. |
Unit | The rule units that the rules generated from this decision table belong to. | Optional, at most once. If omitted, the rules do not belong to any unit. |
Dialect | java or mvel. The dialect used in the actions of the decision table. | Optional, at most once. If omitted, java is imposed. |
ResultSet: There can only be one area .
3、RuleTable What properties can be found below
| Label | Or custom label that begins with | Value | Usage |
|---|---|---|---|
NAME | N | Provides the name for the rule generated from that row. The default is constructed from the text following the RuleTable tag and the row number. | At most one column. |
DESCRIPTION | I | Results in a comment within the generated rule. | At most one column. |
CONDITION | C | Code snippet and interpolated values for constructing a constraint within a pattern in a condition. | At least one per rule table. |
ACTION | A | Code snippet and interpolated values for constructing an action for the consequence of the rule. | At least one per rule table. |
METADATA | @ | Code snippet and interpolated values for constructing a metadata entry for the rule. | Optional, any number of columns. |
See the above figure for specific use
4、 Writing rule attributes
stay ResultSet and ResultTable Rule attributes can be written here .ResultSet Local rule attributes will affect all rules under the same package , and ResultTable The rule properties of this place , Only this rule is affected .ResultTable Higher priority .
The supported rule attributes are :PRIORITY、DATE-EFFECTIVE、DATE-EXPIRES、NO-LOOP、AGENDA-GROUP、ACTIVATION-GROUP、DURATION、TIMER、CALENDAR、AUTO-FOCUS、LOCK-ON-ACTIVE、RULEFLOW-GROUP.
Specific usage : See above ACTIVATION-GROUP Use .
3、 ... and 、 demand
We need to score according to the students' grades , Give the corresponding results . The following rules :
Rules for special treatment :
Rule one : As long as the name is Zhang San Of , Directly determine as optimal
Rule 2 : As long as the name is Li Si Of , If Fraction in 0,60 Between , Think directly of as commonly
Common rules :
Rule three : Fraction in 0,60 Between think is fail,
Rule 4 : Fraction in 60,70 Between think is commonly
Rule five : Fraction in 70,90 Between think is good
Rule 6 : Fraction in 90,100 Between think is optimal
From the rules above , We can see that the name is Zhang San and Li Si Of the students were specially treated .
Four 、 Realization
1、 Project implementation structure diagram

2、 introduce jar package
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-bom</artifactId>
<type>pom</type>
<version>7.69.0.Final</version>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-compiler</artifactId>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-mvel</artifactId>
</dependency>
<!-- Decision table -->
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-decisiontables</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.11</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
</dependencies>
3、 To write kmodule.xml file
<kmodule xmlns="http://www.drools.org/xsd/kmodule">
<kbase name="kabse" packages="rules.decision.tables" default="false">
<ksession name="ksession" default="false" type="stateful"/>
</kbase>
</kmodule>
4、 Write student entity classes
@Getter
@Setter
@ToString
public class Student {
private String name;
// The score can only be in 0-100 Between
private Integer score;
public Student(String name, Integer score) {
this.name = name;
if (null == score || score < 0 || score > 100) {
throw new RuntimeException(" The score can only be in 0-100 Between ");
}
this.score = score;
}
}
5、 Prepare decision table

6、 Convert the decision table to drl file
This step is mainly to check whether our decision table is written correctly , Look at the resulting drl What is the file like .
1、 The decision table is converted to drl File code
/** * The decision table is converted to drl file */
public static void decisionTable2Drl() throws IOException {
Resource resource = ResourceFactory.newClassPathResource("rules/decision/tables/student-score.xlsx", "UTF-8");
InputStream inputStream = resource.getInputStream();
SpreadsheetCompiler compiler = new SpreadsheetCompiler();
String drl = compiler.compile(inputStream, InputType.XLS);
log.info(" Decision table conversion drl The content is :\r{}", drl);
// Check it out drl Is there a problem with the file
KieHelper kieHelper = new KieHelper();
Results results = kieHelper.addContent(drl, ResourceType.DRL).verify();
List<Message> messages = results.getMessages(Message.Level.ERROR);
if (null != messages && !messages.isEmpty()) {
for (Message message : messages) {
log.error(message.getText());
}
}
}
2、 Translate into concrete drl File for
package rules.decision.tables;
//generated from Decision Table
import java.lang.StringBuilder;
import com.huan.drools.Student;
global java.lang.StringBuilder resultsInfo;
// rule values at B15, header at B10
rule "student-score-name-1"
/* 1、 Special treatment for Zhang San 2、 The name of the custom rule */
salience 65535
activation-group "score"
when
$stu: Student(name == " Zhang San ")
then
resultsInfo.append(" Special treatment for Zhang San :");
System.out.println(" The rules :" + drools.getRule().getName() + " Yes .");
resultsInfo.append(" optimal ");
System.out.println(" The rules :" + drools.getRule().getName() + " Yes .");
end
// rule values at B16, header at B10
rule "student-score_16"
salience 65534
activation-group "score"
when
$stu: Student(name == " Li Si ", score > 0 && score < 60)
then
resultsInfo.append(" Special treatment of the fourth part of Li :");
System.out.println(" The rules :" + drools.getRule().getName() + " Yes .");
resultsInfo.append(" commonly ");
System.out.println(" The rules :" + drools.getRule().getName() + " Yes .");
end
// rule values at B17, header at B10
rule "student-score_17"
salience 65533
activation-group "score"
when
$stu: Student(score > 0 && score < 60)
then
resultsInfo.append(" fail, ");
System.out.println(" The rules :" + drools.getRule().getName() + " Yes .");
end
// rule values at B18, header at B10
rule "student-score_18"
salience 65532
activation-group "score"
when
$stu: Student(score > 60 && score < 70)
then
resultsInfo.append(" commonly ");
System.out.println(" The rules :" + drools.getRule().getName() + " Yes .");
end
// rule values at B19, header at B10
rule "student-score_19"
salience 65531
activation-group "score"
when
$stu: Student(score > 70 && score < 90)
then
resultsInfo.append(" good ");
System.out.println(" The rules :" + drools.getRule().getName() + " Yes .");
end
// rule values at B20, header at B10
rule "student-score_20"
salience 65530
activation-group "score"
when
$stu: Student(score > 90 && score < 100)
then
resultsInfo.append(" optimal ");
System.out.println(" The rules :" + drools.getRule().getName() + " Yes .");
end
You can see from the top The first rule Of Rule name It's different , And there is some descriptive information , This is specially handled in the decision table .
7、 test
1、 Write test code
package com.huan.drools;
import lombok.extern.slf4j.Slf4j;
import org.drools.decisiontable.InputType;
import org.drools.decisiontable.SpreadsheetCompiler;
import org.kie.api.KieServices;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.io.Resource;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.kie.internal.utils.KieHelper;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/** * drools Use of decision tables */
@Slf4j
public class DroolsDecisionTableApplication {
public static void main(String[] args) throws IOException {
decisionTable2Drl();
KieServices kieServices = KieServices.get();
KieContainer kieContainer = kieServices.newKieClasspathContainer();
// Although Zhang San had to 20 branch , But judging by the rules , The result should be optimal
invokedDecisionTable(kieContainer, new Student(" Zhang San ", 20));
// Although Li Si had to 20 branch , But judging by the rules , The result should be commonly
invokedDecisionTable(kieContainer, new Student(" Li Si ", 20));
// Liside 75 branch , But judging by the rules , The result should be good
invokedDecisionTable(kieContainer, new Student(" Li Si ", 75));
// Wang Wude 59 branch , But judging by the rules , The result should be fail,
invokedDecisionTable(kieContainer, new Student(" Wang Wu ", 59));
// Zhaoliude 20 branch , But judging by the rules , The result should be commonly
invokedDecisionTable(kieContainer, new Student(" Zhao Liu ", 65));
// Qian Qide 20 branch , But judging by the rules , The result should be good
invokedDecisionTable(kieContainer, new Student(" Qian Qi ", 75));
// Libade 20 branch , But judging by the rules , The result should be optimal
invokedDecisionTable(kieContainer, new Student(" Li ba ", 95));
}
public static void invokedDecisionTable(KieContainer kieContainer, Student student) {
System.out.println("\r");
KieSession kieSession = kieContainer.newKieSession("ksession");
StringBuilder result = new StringBuilder();
kieSession.setGlobal("resultsInfo", result);
kieSession.insert(student);
kieSession.fireAllRules();
kieSession.dispose();
System.out.println(" Rule execution results :" + result);
}
/** * The decision table is converted to drl file */
public static void decisionTable2Drl() throws IOException {
Resource resource = ResourceFactory.newClassPathResource("rules/decision/tables/student-score.xlsx", "UTF-8");
InputStream inputStream = resource.getInputStream();
SpreadsheetCompiler compiler = new SpreadsheetCompiler();
String drl = compiler.compile(inputStream, InputType.XLS);
log.info(" Decision table conversion drl The content is :\r{}", drl);
// Check it out drl Is there a problem with the file
KieHelper kieHelper = new KieHelper();
Results results = kieHelper.addContent(drl, ResourceType.DRL).verify();
List<Message> messages = results.getMessages(Message.Level.ERROR);
if (null != messages && !messages.isEmpty()) {
for (Message message : messages) {
log.error(message.getText());
}
}
}
}
2、 test result

It can be seen from the above figure , Our rules have been implemented normally .
5、 ... and 、 Complete code
https://gitee.com/huan1993/spring-cloud-parent/tree/master/drools/drools-decision-table
6、 ... and 、 Reference documents
边栏推荐
- Differences between nodes and sharding in ES cluster
- drools动态增加、修改、删除规则
- 史上最易懂的f-string教程,收藏這一篇就够了
- 记录一下MySql update会锁定哪些范围的数据
- Those logs in MySQL
- The differences and relationships among port, targetport, nodeport and containerport in kubenetes
- How does Premiere (PR) import the preset mogrt template?
- Yygh-9-make an appointment to place an order
- Intel 内部指令 --- AVX和AVX2学习笔记
- CDH6之Sqoop添加数据库驱动
猜你喜欢

Sparkcontext: error initializing sparkcontext solution

自然语言处理系列(一)——RNN基础

Take you ten days to easily finish the finale of go micro services (distributed transactions)

SparkContext: Error initializing SparkContext解决方法

Deep understanding of P-R curve, ROC and AUC

H5, add a mask layer to the page, which is similar to clicking the upper right corner to open it in the browser

堆(優先級隊列)

AI中台技术调研

YYGH-BUG-04

mysql索引和事务
随机推荐
MySQL与PostgreSQL抓取慢sql的方法
PyTorch nn.RNN 参数全解析
计算二叉树的最大路径和
Fastdateformat why thread safe
浅谈sklearn中的数据预处理
Experiment of connecting mobile phone hotspot based on Arduino and esp8266 (successful)
(C language) octal conversion decimal
Full link voltage measurement
Leetcode14 longest public prefix
Applet link generation
Repeat, tile and repeat in pytorch_ The difference between interleave
ORB-SLAM2不同线程间的数据共享与传递
排序---
Sub thread get request
Leetcode122 买卖股票的最佳时机 II
When uploading a file, the server reports an error: iofileuploadexception: processing of multipart / form data request failed There is no space on the device
SVO2系列之深度滤波DepthFilter
寻找二叉树中任意两个数的公共祖先
Post request body content cannot be retrieved repeatedly
Gaode map test case