当前位置:网站首页>Drools (3): drools basic syntax (1)
Drools (3): drools basic syntax (1)
2022-07-26 07:02:00 【Undead bird. Alexander. Wolf cub】
1 Composition of rule file
drl yes Drools Rule Language Abbreviation . In the rule ⽂ Write specific rules in the document .
⼀ A complete set of rules ⽂ The contents of this document are as follows :
package: Package name ,package Corresponding no ⼀ It must be real ⽬ record , You can write whatever you want com.abc, Same as ⼀ Under a bag drl⽂ Pieces can visit each other
import:⽤ Yu Dao ⼊ Class or static ⽅ Law
global: Global variables
function:⾃ Defined function
query: Inquire about
rule end: Regular form
2 Regular syntax structure
⼀ A rule usually consists of three parts : Properties section (attribute) 、 Condition part (LHS) And results section (RHS)
rule "ruleName" //rule keyword , Indicates the beginning of the rule , The parameter is the rule only ⼀ name
attributes // Rule properties , yes rule And when Parameters between , For optional
when // keyword , after ⾯ It's the conditional part of the rule
LHS //Left Hand Side, It's the conditional part of the rule
then // after ⾯ Follow the result part of the rule
RHS // Is the result of rules or ⾏ by
end // Express ⼀ The end of the rule 3 The rule syntax of the condition part
LHS(Left Hand Side): It is the pass of the conditional part of the rule ⽤ name . It consists of zero or more conditional elements . If LHS It's empty , Then it will be regarded as always true Conditional element of .( Left ⼿ edge )
LHS Partly from ⼀ One or more conditions make up , Conditions ⼜ be called pattern.
pattern The grammatical structure of is : Bind variable name :Object(Field constraint )The bound variable name can be omitted , Usually, the name of the binding variable name ⼀ It is generally recommended to $ Start . If the binding variable name is defined , Can In the regular body RHS Partially make ⽤ Bind the variable name to operate the corresponding Fact object .Field The constraint part is to return true perhaps false Of 0 One or more expressions .
// The rules 1:100 Yuan of the following , No bonus points
rule "score_1"
When
//⼯ Must exist in the memory Order This type of Fact object ----- Type constraint
//Fact Object's amout Attribute value must be ⼩ Is equal to 100------ Attribute constraints
$s : Order(amout <= 100)
Then
$s.setScore(0);
System.out.println(" Successfully matched to rule 1:100 Yuan of the following , No bonus points ");
endIf LHS If the part is empty , Then the engine will ⾃ Dynamic add ⼀ individual eval(true) Conditions , Because the condition always returns true, the With LHS Empty rules always return true
3.1 Constraint connection
stay LHS among , Can contain 0~n Conditions , Multiple pattern You can take ⽤“&&” (and) 、 “||”(or) and “,”(and) To achieve , Or not , The default connection is and.
// The rules 2:100 element -500 element Add 100 branch
rule "score_2"
when
$s : Order(amout > 100 && amout <= 500)
then
$s.setScore(100);
System.out.println(" Successfully matched to rule 2:100 element -500 element Add 100 branch ");
end3.2 Comparison operator
stay Drools When the Communist Party of China provided ⼗⼆ Types of ⽐ Better operator , Namely : >、 >=、 <、 <=、 = =、 !=、 contains、 not contains、memberof、not memberof、matches、not matches; Here ⼗⼆ Among the three types of comparison operators , The first six are more commonly used comparison operators
| Symbol | explain |
| > | Greater than |
| < | Less than |
| >= | Greater than or equal to |
| <= | Less than or equal to |
| == | be equal to |
| != | It's not equal to |
| contains | Check ⼀ individual Fact Whether a property value of an object contains ⼀ Specified object values |
| not contains | Check ⼀ individual Fact Whether a property value of an object does not contain ⼀ Specified object values |
| memberOf | Judge ⼀ individual Fact Whether a property of the object is ⼀ In one or more sets |
| not memberOf | Judge ⼀ individual Fact Whether a property of the object is not ⼀ In one or more sets |
| matches | Judge ⼀ individual Fact Whether the properties of the object are consistent with the provided standard Java Regular expressions go into ⾏ matching |
| not matches | Judge ⼀ individual Fact Whether the properties of the object are different from the provided standard Java Regular expressions go into ⾏ matching |
Example :
The first ⼀ Step : Create entity class ,⽤ For testing ⽐ Better operator
package com.xiongpeng.entity;
import java.util.List;
public class Customer {
// Name of customer
private String name;
private List<Order> orderList;
// Order set
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Order> getOrderList() {
return orderList;
}
public void setOrderList(List<Order> orderList) {
this.orderList = orderList;
}
}The first ⼆ Step : stay /resources/rules Create rules under ⽂ Pieces of customer-rules.drl
package rules
import com.xiongpeng.entity.*;
// test contains The rules
rule "rule1"
when
$order:Order();
$customer:Customer(orderList contains $order);
then
System.out.println(" test contains Rules trigger :"+$customer.getName());
end
// test not contains The rules
rule "rule2"
when
$order:Order();
$customer:Customer(orderList not contains $order);
then
System.out.println(" test not contains Rules trigger :"+$customer.getName());
end
// test ⽐ Better operator matches
rule "rule3"
when
Customer(name matches " Zhang .*")
then
System.out.println(" test ⽐ Better operator matches Trigger ...");
end
// test ⽐ Better operator not matches
rule "rule4"
when
Customer(name not matches " Zhang .*")
then
System.out.println(" test ⽐ Better operator not matches Trigger ...");
endThe third step : Write unit tests
@Test
public void test2() {
KieServices kieServices = KieServices.Factory.get();
KieContainer kieContainer = kieServices.getKieClasspathContainer();
// Conversation object ,⽤ Interact with the rule engine
KieSession kieSession = kieContainer.newKieSession();
// Construct order object , Set up order ⾦ forehead , The integral calculated by the rule engine
Order order = new Order();
// Matching rules :$order:Order();
kieSession.insert(order);
Customer customer = new Customer();
List<Order> orderList = new ArrayList<Order>();
// Matching rules : $customer:Customer(orderList contains $order);
// orderList.add(order);
customer.setOrderList(orderList);
customer.setName("Jack");
// Give the data to the rule engine , The rule engine will enter ⾏ Rule matching
kieSession.insert(customer);
// Activate rule engine , If the match is successful, execute ⾏ The rules
kieSession.fireAllRules();
// Close session
kieSession.dispose();
}The results are as follows :

The above results call all rules when calling , Connect the score-rules.drl Rules are called , In this case , We can call the specified rules .
Be careful :
Execute specified rules
We're adjusting ⽤ Rule code , All rules that meet the conditions will be executed . So if we just want to cling ⾏ How to implement one of the rules ?
Drools For us ⽅ Formula is implemented by rule filter ⾏ Specify the rules . For the rules ⽂ There is no need to make any modification , It just needs to be modified Java The code can be ,
as follows :
@Test
public void test3() {
KieServices kieServices = KieServices.Factory.get();
KieContainer kieContainer = kieServices.getKieClasspathContainer();
// Conversation object ,⽤ Interact with the rule engine
KieSession kieSession = kieContainer.newKieSession();
// Construct order object , Set up order ⾦ forehead , The integral calculated by the rule engine
Order order = new Order();
// Matching rules :$order:Order();
kieSession.insert(order);
Customer customer = new Customer();
List<Order> orderList = new ArrayList<Order>();
// Matching rules : $customer:Customer(orderList contains $order);
// orderList.add(order);
customer.setOrderList(orderList);
customer.setName("Jack");
// Give the data to the rule engine , The rule engine will enter ⾏ Rule matching
kieSession.insert(customer);
// Activate rule engine , If the match is successful, execute ⾏ The rules
kieSession.fireAllRules(new RuleNameEqualsAgendaFilter("rule4"));
// Close session
kieSession.dispose();
}Key statement :
// Implement execution only through rule filters ⾏ Specify the rules
kieSession.fireAllRules(new RuleNameEqualsAgendaFilter("rule4"));The results are as follows :

边栏推荐
- Getting started with kernel PWN (5)
- PMP customs formula, don't hurry to recite it
- 火焰图分析Flink反压
- 10 papers of ant security laboratory were included by ccf-a top meeting to explore the realization of AI credibility from the perspective of algorithm
- Depth cloning and reflection of typescript class objects
- docker修改挂载到宿主机上的mysql配置文件不生效?
- Database performance test (MySQL)
- 数据库性能测试(mysql)
- 20220725 自动控制原理中的卷积Convolution
- one hundred and twenty-three million one hundred and twenty-three thousand one hundred and twenty-three
猜你喜欢

7. Reverse integer integer

On stock price prediction model (3): are you falling into the trap of machine learning

String and memory functions

Flame diagram analysis Flink backpressure

Getting started with kernel PWN (5)

Contents mismatch at: 08000000H (Flash=FFH Required=00H) ! Too many errors to display !
![Rust语言- Slice(切片)类型(&[u8])](/img/d1/68c73c8b34b848212083c08df3137f.png)
Rust语言- Slice(切片)类型(&[u8])

Question: can't download sh shellcheck Please install it manually and some commands of shell script
![[graduation season _ advanced technology Er] farewell to yourself who has been confused for the past two years. Regroup, junior I'm coming](/img/04/3121514fcd8fcf1c939cbca7f4c67a.jpg)
[graduation season _ advanced technology Er] farewell to yourself who has been confused for the past two years. Regroup, junior I'm coming

“蔚来杯“2022牛客暑期多校训练营1补题记录(ACDGIJ)
随机推荐
"Niuke | daily question" inverse Polish expression
IR tool in JIT and download, compile and use of jitwatch
28. Implement strstr() implement strstr()
Is there any online account opening process of Huatai Securities? Is online account opening safe
20220725 compensator in automatic control principle
File server fastdfs
Contents mismatch at: 08000000H (Flash=FFH Required=00H) ! Too many errors to display !
shape 和 size() 区别
Opengauss simple version installation error
Benefits of the builder model
How does the national standard gb28181 protocol easygbs platform realize device video recording and set streaming IP?
Development stage of source code encryption technology
Is it safe to invest in treasury bonds in 2022? How do individuals buy treasury bonds?
在第一次使用德国小鸡要注意的地方
MySQL isolation level transactions
Can you learn fast and well with dual stream network? Harbin Institute of Technology & Microsoft proposed a distillation dual encoder model for visual language understanding, which can achieve fast an
NiO implementation
String and memory functions
SQL shell (PSQL) tool under PostgreSQL
Acwing- daily question