规则引擎Drools使用,0基础入门规则引擎Drools(二)高级语法

文章目录

系列文章索引

规则引擎Drools使用,0基础入门规则引擎Drools(一)基础入门
规则引擎Drools使用,0基础入门规则引擎Drools(二)高级语法
规则引擎Drools使用,0基础入门规则引擎Drools(三)整合springboot
规则引擎Drools使用,0基础入门规则引擎Drools(四)WorkBench控制台
规则引擎Drools使用,0基础入门规则引擎Drools(五)实战+决策表

五、规则属性

前面我们已经知道了规则体的构成如下:

java 复制代码
rule "ruleName"
    attributes
    when
        LHS
    then
        RHS
end

Drools中提供的属性如下表(部分属性):

属性名 说明
salience 指定规则执行优先级
dialect 指定规则使用的语言类型,取值为java和mvel
enabled 指定规则是否启用
date-effective 指定规则生效时间
date-expires 指定规则失效时间
activation-group 激活分组,具有相同分组名称的规则只能有一个规则触发
agenda-group 议程分组,只有获取焦点的组中的规则才有可能触发
timer 定时器,指定规则触发的时间
auto-focus 自动获取焦点,一般结合agenda-group一起使用
no-loop 防止死循环

1、enabled属性

enabled属性对应的取值为true和false,默认值为true。

用于指定当前规则是否启用,如果设置的值为false则当前规则无论是否匹配成功都不会触发。

java 复制代码
rule "rule_comparison_notMemberOf"
    //指定当前规则不可用,当前规则无论是否匹配成功都不会执行
    enabled false
    when
        ComparisonOperatorEntity(names not memberOf list)
    then
        System.out.println("规则rule_comparison_notMemberOf触发");
end

2、dialect属性

dialect属性用于指定当前规则使用的语言类型,取值为java和mvel,默认值为java。

注:mvel是一种基于java语法的表达式语言。

mvel像正则表达式一样,有直接支持集合、数组和字符串匹配的操作符。

mvel还提供了用来配置和构造字符串的模板语言。

mvel表达式内容包括属性表达式,布尔表达式,方法调用,变量赋值,函数定义等。

3、salience属性

salience属性用于指定规则的执行优先级,取值类型为Integer。数值越大越优先执行。每个规则都有一个默认的执行顺序,如果不设置salience属性,规则体的执行顺序为由上到下。

可以通过创建规则文件salience.drl来测试salience属性,内容如下:

java 复制代码
//当前规则文件用于测试执行优先级
package testsalience

//定义第一个规则
rule "rule_1"
    salience 10//指定规则执行的优先级,数值越大越优先
    when
        eval(true)//返回true,即当前规则匹配成功
    then
        System.out.println("规则:rule_1触发了...");
end

//定义第二个规则
rule "rule_2"
    salience 11
    when
        eval(true)//返回true,即当前规则匹配成功
    then
        System.out.println("规则:rule_2触发了...");
end

//定义第三个规则
rule "rule_3"
    salience 5
    when
        eval(true)//返回true,即当前规则匹配成功
    then
        System.out.println("规则:rule_3触发了...");
end

通过控制台可以看到,规则文件执行的顺序是按照我们设置的salience值由大到小顺序执行的。

建议在编写规则时使用salience属性明确指定执行优先级。

4、no-loop属性

no-loop属性用于防止死循环,当规则通过update之类的函数修改了Fact对象时,可能使当前规则再次被激活从而导致死循环。取值类型为Boolean,默认值为false。测试步骤如下:

第一步:编写规则文件/resource/rules/noloop.drl

java 复制代码
//当前规则文件用于测试noloop防止规则执行时死循环问题
package testnoloop
import com.drools.Student

rule "rule_noloop"
    no-loop true//使用no-loop解决死循环问题
    when
        $s:Student(age == 50)
    then
        update($s);//调用update方法会导致相关规则重新匹配
        System.out.println("规则:rule_noloop触发了...");
end

通过控制台可以看到,我们没有设置no-loop属性的值,所以发生了死循环。设置no-loop的值为true再次测试则不会发生死循环。

5、activation-group属性

activation-group属性是指激活分组,取值为String类型。具有相同分组名称的规则只能有一个规则被触发

第一步:编写规则文件/resources/rules/activationgroup.drl

java 复制代码
//当前规则文件用于测试activation-group属性
package testactivationgroup

rule "rule_activationgroup_1"
    activation-group "mygroup"//对于同一个组内的规则,只能有一个触发
    salience 5
    when
        //如果条件不写,默认为true,表示规则匹配成功
    then
        System.out.println("规则:rule_activationgroup_1触发了...");
end

rule "rule_activationgroup_2"
    activation-group "mygroup"
    salience 10
    when
        //如果条件不写,默认为true,表示规则匹配成功
    then
        System.out.println("规则:rule_activationgroup_2触发了...");
end

通过控制台可以发现,上面的两个规则因为属于同一个分组,所以只有一个触发了。同一个分组中的多个规则如果都能够匹配成功,具体哪一个最终能够被触发可以通过salience属性确定。

6、agenda-group属性

agenda-group属性为议程分组,属于另一种可控的规则执行方式。用户可以通过设置agenda-group来控制规则的执行,只有获取焦点的组中的规则才会被触发。

第一步:创建规则文件/resources/rules/agendagroup.drl

java 复制代码
package testagendagroup
/*
    此规则文件用于测试agenda-group属性
*/
rule "rule_agendagroup_1"
    agenda-group "myagendagroup_1"
    when
    then
        System.out.println("规则rule_agendagroup_1触发");
end
​
rule "rule_agendagroup_2"
    agenda-group "myagendagroup_1"
    when
    then
        System.out.println("规则rule_agendagroup_2触发");
end
//========================================================
rule "rule_agendagroup_3"
    agenda-group "myagendagroup_2"
    when
    then
        System.out.println("规则rule_agendagroup_3触发");
end
​
rule "rule_agendagroup_4"
    agenda-group "myagendagroup_2"
    when
    then
        System.out.println("规则rule_agendagroup_4触发");
end

第二步:编写单元测试

java 复制代码
KieServices kieServices = KieServices.Factory.get();
KieContainer kieClasspathContainer = kieServices.getKieClasspathContainer();
KieSession kieSession = kieClasspathContainer.newKieSession();
​
//设置焦点,对应agenda-group分组中的规则才可能被触发
kieSession.getAgenda().getAgendaGroup("myagendagroup_1").setFocus();
​
kieSession.fireAllRules();
kieSession.dispose();

通过控制台可以看到,只有获取焦点的分组中的规则才会触发。与activation-group不同的是,activation-group定义的分组中只能够有一个规则可以被触发,而agenda-group分组中的多个规则都可以被触发。

7、auto-focus属性

auto-focus属性为自动获取焦点,取值类型为Boolean,默认值为false。一般结合agenda-group属性使用,当一个议程分组未获取焦点时,可以设置auto-focus属性来控制。

第一步:修改/resources/rules/agendagroup.drl文件内容如下

java 复制代码
package testagendagroup
​
rule "rule_agendagroup_1"
    agenda-group "myagendagroup_1"
    when
    then
        System.out.println("规则rule_agendagroup_1触发");
end
​
rule "rule_agendagroup_2"
    agenda-group "myagendagroup_1"
    when
    then
        System.out.println("规则rule_agendagroup_2触发");
end
//========================================================
rule "rule_agendagroup_3"
    agenda-group "myagendagroup_2"
    auto-focus true //自动获取焦点
    when
    then
        System.out.println("规则rule_agendagroup_3触发");
end
​
rule "rule_agendagroup_4"
    agenda-group "myagendagroup_2"
    auto-focus true //自动获取焦点
    when
    then
        System.out.println("规则rule_agendagroup_4触发");
end

第二步:编写单元测试

java 复制代码
KieServices kieServices = KieServices.Factory.get();
KieContainer kieClasspathContainer = kieServices.getKieClasspathContainer();
KieSession kieSession = kieClasspathContainer.newKieSession();
kieSession.fireAllRules();
kieSession.dispose();

通过控制台可以看到,设置auto-focus属性为true的规则都触发了。

8、timer属性

timer属性可以通过定时器的方式指定规则执行的时间,使用方式有两种:

方式一:timer (int: <initial delay> <repeat interval>?)

此种方式遵循java.util.Timer对象的使用方式,第一个参数表示几秒后执行,第二个参数表示每隔几秒执行一次,第二个参数为可选。

方式二:timer(cron: <cron expression>)

此种方式使用标准的unix cron表达式的使用方式来定义规则执行的时间。

第一步:创建规则文件/resources/rules/timer.drl

java 复制代码
package testtimer
import java.text.SimpleDateFormat
import java.util.Date
/*
    此规则文件用于测试timer属性
*/
​
rule "rule_timer_1"
    timer (5s 2s) //含义:5秒后触发,然后每隔2秒触发一次
    when
    then
        System.out.println("规则rule_timer_1触发,触发时间为:" + 
                         new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
end
​
rule "rule_timer_2"
    timer (cron:0/1 * * * * ?) //含义:每隔1秒触发一次
    when
    then
        System.out.println("规则rule_timer_2触发,触发时间为:" + 
                         new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
end

第二步:编写单元测试

java 复制代码
KieServices kieServices = KieServices.Factory.get();
KieContainer kieClasspathContainer = kieServices.getKieClasspathContainer();
final KieSession kieSession = kieClasspathContainer.newKieSession();
​
new Thread(new Runnable() {
    public void run() {
        //启动规则引擎进行规则匹配,直到调用halt方法才结束规则引擎
        kieSession.fireUntilHalt();
    }
}).start();
​
Thread.sleep(10000);
//结束规则引擎
kieSession.halt();
kieSession.dispose();

注意:单元测试的代码和以前的有所不同,因为我们规则文件中使用到了timer进行定时执行,需要程序能够持续一段时间才能够看到定时器触发的效果。

9、date-effective属性

date-effective属性用于指定规则的生效时间,即只有当前系统时间大于等于设置的时间或者日期规则才有可能触发。默认日期格式为:dd-MMM-yyyy。用户也可以自定义日期格式。

第一步:编写规则文件/resources/rules/dateeffective.drl

java 复制代码
package testdateeffective
/*
    此规则文件用于测试date-effective属性
*/
rule "rule_dateeffective_1"
    date-effective "2023-11-22 10:00"//date-effective属性用于指定当前规则生效时间
    when
    then
        System.out.println("规则rule_dateeffective_1触发");
end

第二步:编写单元测试

java 复制代码
//设置日期格式
System.setProperty("drools.dateformat","yyyy-MM-dd HH:mm");
KieServices kieServices = KieServices.Factory.get();
KieContainer kieClasspathContainer = kieServices.getKieClasspathContainer();
KieSession kieSession = kieClasspathContainer.newKieSession();
kieSession.fireAllRules();
kieSession.dispose();

注意:上面的代码需要设置日期格式,否则我们在规则文件中写的日期格式和默认的日期格式不匹配程序会报错。

10、date-expires属性

date-expires属性用于指定规则的失效时间,即只有当前系统时间小于设置的时间或者日期规则才有可能触发。默认日期格式为:dd-MMM-yyyy。用户也可以自定义日期格式。

第一步:编写规则文件/resource/rules/dateexpires.drl

java 复制代码
package testdateexpires
/*
    此规则文件用于测试date-expires属性
*/
​
rule "rule_dateexpires_1"
    date-expires "2023-11-22 10:00" //date-expires属性用于指定当前规则的失效时间
    when
    then
        System.out.println("规则rule_dateexpires_1触发");
end

第二步:编写单元测试

java 复制代码
//设置日期格式
System.setProperty("drools.dateformat","yyyy-MM-dd HH:mm");
KieServices kieServices = KieServices.Factory.get();
KieContainer kieClasspathContainer = kieServices.getKieClasspathContainer();
KieSession kieSession = kieClasspathContainer.newKieSession();
kieSession.fireAllRules();
kieSession.dispose();

注意:上面的代码需要设置日期格式,否则我们在规则文件中写的日期格式和默认的日期格式不匹配程序会报错。

六、Drools高级语法

1、global全局变量

global关键字用于在规则文件中定义全局变量,它可以让应用程序的对象在规则文件中能够被访问。可以用来为规则文件提供数据或服务。

语法结构为:global 对象类型 对象名称

在使用global定义的全局变量时有两点需要注意:

1、如果对象类型为包装类型时,在一个规则中改变了global的值,那么只针对当前规则有效,对其他规则中的global不会有影响。可以理解为它是当前规则代码中的global副本,规则内部修改不会影响全局的使用。

2、如果对象类型为集合类型或JavaBean时,在一个规则中改变了global的值,对java代码和所有规则都有效。

下面我们通过代码进行验证:

第一步:创建UserService类

java 复制代码
public class UserService {
    public void save(){
        System.out.println("UserService.save()...");
    }
}

第二步:编写规则文件/resources/rules/global.drl

java 复制代码
package testglobal
/*
    此规则文件用于测试global全局变量
*/
​
global java.lang.Integer count //定义一个包装类型的全局变量
global com.drools.UserService userService //定义一个JavaBean类型的全局变量
global java.util.List gList //定义一个集合类型的全局变量
​
rule "rule_global_1"
    when
    then
        count += 10; //全局变量计算,只对当前规则有效,其他规则不受影响
        userService.save();//调用全局变量的方法
        gList.add("itcast");//向集合类型的全局变量中添加元素,Java代码和所有规则都受影响
        gList.add("itglobal");
        System.out.println("count=" + count);
        System.out.println("gList.size=" + gList.size());
end
​
rule "rule_global_2"
    when
    then
        userService.save();
        System.out.println("count=" + count);
        System.out.println("gList.size=" + gList.size());
end

第三步:编写单元测试

java 复制代码
KieServices kieServices = KieServices.Factory.get();
KieContainer kieClasspathContainer = kieServices.getKieClasspathContainer();
KieSession kieSession = kieClasspathContainer.newKieSession();
​
//设置全局变量,名称和类型必须和规则文件中定义的全局变量名称对应
kieSession.setGlobal("userService",new UserService());
kieSession.setGlobal("count",5);
List list = new ArrayList();//size为0
kieSession.setGlobal("gList",list);
​
kieSession.fireAllRules();
kieSession.dispose();
​
//因为在规则中为全局变量添加了两个元素,所以现在的size为2
System.out.println(list.size());

结果:

UserService.save()...

count=15

gList.size=2

UserService.save()...

count=5

gList.size=2

2

2、query查询

query查询提供了一种查询working memory中符合约束条件的Fact对象的简单方法。它仅包含规则文件中的LHS部分,不用指定"when"和"then"部分并且以end结束。具体语法结构如下:

java 复制代码
query 查询的名称(可选参数)
    LHS
end

具体操作步骤:

第一步:编写规则文件/resources/rules/query.drl

java 复制代码
package testquery
import com.drools.Student
/*
    此规则文件用于测试query查询
*/
​
//不带参数的查询
//当前query用于查询Working Memory中age>10的Student对象
query "query_1"
    $student:Student(age > 10)
end
​
//带有参数的查询
//当前query用于查询Working Memory中age>10同时name需要和传递的参数name相同的Student对象
query "query_2"(String sname)
    $student:Student(age > 20 && name == sname)
end

第二步:编写单元测试

java 复制代码
KieServices kieServices = KieServices.Factory.get();
KieContainer kieClasspathContainer = kieServices.getKieClasspathContainer();
KieSession kieSession = kieClasspathContainer.newKieSession();
​
Student student1 = new Student();
student1.setName("张三");
student1.setAge(12);
​
Student student2 = new Student();
student2.setName("李四");
student2.setAge(8);
​
Student student3 = new Student();
student3.setName("王五");
student3.setAge(22);
​
//将对象插入Working Memory中
kieSession.insert(student1);
kieSession.insert(student2);
kieSession.insert(student3);
​
//调用规则文件中的查询
QueryResults results1 = kieSession.getQueryResults("query_1");
int size = results1.size();
System.out.println("size=" + size);
for (QueryResultsRow row : results1) {
    Student student = (Student) row.get("$student");
    System.out.println(student);
}
​
//调用规则文件中的查询
QueryResults results2 = kieSession.getQueryResults("query_2","王五");
size = results2.size();
System.out.println("size=" + size);
for (QueryResultsRow row : results2) {
    Student student = (Student) row.get("$student");
    System.out.println(student);
}
//kieSession.fireAllRules();
kieSession.dispose();

结果:

size=2

com.drools.Student@74cec793

com.drools.Student@ec0c838

size=1

com.drools.Student@ec0c838

3、function函数

function关键字用于在规则文件中定义函数,就相当于java类中的方法一样。可以在规则体中调用定义的函数。使用函数的好处是可以将业务逻辑集中放置在一个地方,根据需要可以对函数进行修改。

函数定义的语法结构如下:

java 复制代码
function 返回值类型 函数名(可选参数){
    //逻辑代码
}

具体操作步骤:

第一步:编写规则文件/resources/rules/function.drl

java 复制代码
package testfunction
import com.itheima.drools.entity.Student
/*
    此规则文件用于测试function函数
*/
​
//定义一个函数
function String sayHello(String name){
    return "hello " + name;
}
​
rule "rule_function_1"
    when
        $student:Student(name != null)
    then
        //调用上面定义的函数
        String ret = sayHello($student.getName());
        System.out.println(ret);
end

第二步:编写单元测试

java 复制代码
KieServices kieServices = KieServices.Factory.get();
KieContainer kieClasspathContainer = kieServices.getKieClasspathContainer();
KieSession kieSession = kieClasspathContainer.newKieSession();
​
Student student = new Student();
student.setName("小明");
​
kieSession.insert(student);
​
kieSession.fireAllRules();
kieSession.dispose();

4、LHS加强

(1)复合值限制in/not in

复合值限制是指超过一种匹配值的限制条件,类似于SQL语句中的in关键字。Drools规则体中的LHS部分可以使用in或者not in进行复合值的匹配。具体语法结构如下:

Object(field in (比较值1,比较值2...))

举例:

java 复制代码
$s:Student(name in ("张三","李四","王五"))
$s:Student(name not in ("张三","李四","王五"))

(2)条件元素eval

eval用于规则体的LHS部分,并返回一个Boolean类型的值。语法结构如下:

eval(表达式)

举例:

java 复制代码
eval(true)
eval(false)
eval(1 == 1)

(3)条件元素not

not用于判断Working Memory中是否存在某个Fact对象,如果不存在则返回true,如果存在则返回false。语法结构如下:

not Object(可选属性约束)

举例:

java 复制代码
not Student()
not Student(age < 10)

(4)条件元素exists

exists的作用与not相反,用于判断Working Memory中是否存在某个Fact对象,如果存在则返回true,不存在则返回false。语法结构如下:

exists Object(可选属性约束)

举例:

java 复制代码
exists Student()
exists Student(age < 10 && name != null)

可能有人会有疑问,我们前面在LHS部分进行条件编写时并没有使用exists也可以达到判断Working Memory中是否存在某个符合条件的Fact元素的目的,那么我们使用exists还有什么意义?

两者的区别:当向Working Memory中加入多个满足条件的Fact对象时,使用了exists的规则执行一次,不使用exists的规则会执行多次。

例如:

规则文件(只有规则体):

java 复制代码
rule "使用exists的规则"
    when
        exists Student()
    then
        System.out.println("规则:使用exists的规则触发");
end
​
rule "没有使用exists的规则"
    when
        Student()
    then
        System.out.println("规则:没有使用exists的规则触发");
end

Java代码:

java 复制代码
kieSession.insert(new Student());
kieSession.insert(new Student());
kieSession.fireAllRules();

上面第一个规则只会执行一次,因为Working Memory中存在两个满足条件的Fact对象,第二个规则会执行两次。

(5)规则继承

规则之间可以使用extends关键字进行规则条件部分的继承,类似于java类之间的继承。

例如:

java 复制代码
rule "rule_1"
    when
        Student(age > 10)
    then
        System.out.println("规则:rule_1触发");
end
​
rule "rule_2" extends "rule_1" //继承上面的规则
    when
        /*
        此处的条件虽然只写了一个,但是从上面的规则继承了一个条件,
        所以当前规则存在两个条件,即Student(age < 20)和Student(age > 10)
        */
        Student(age < 20) 
    then
        System.out.println("规则:rule_2触发");
end

5、RHS加强

RHS部分是规则体的重要组成部分,当LHS部分的条件匹配成功后,对应的RHS部分就会触发执行。一般在RHS部分中需要进行业务处理。

在RHS部分Drools为我们提供了一个内置对象,名称就是drools

(1)halt 终止后续规则

halt方法的作用是立即终止后面所有规则的执行。

java 复制代码
package testhalt
rule "rule_halt_1"
    when
    then
        System.out.println("规则:rule_halt_1触发");
        drools.halt();//立即终止后面所有规则执行
end
​
//当前规则并不会触发,因为上面的规则调用了halt方法导致后面所有规则都不会执行
rule "rule_halt_2"
    when
    then
        System.out.println("规则:rule_halt_2触发");
end

(2)getWorkingMemory

getWorkingMemory方法的作用是返回工作内存对象。

java 复制代码
package testgetWorkingMemory
rule "rule_getWorkingMemory"
    when
    then
        System.out.println(drools.getWorkingMemory());
end

(3)getRule

getRule方法的作用是返回规则对象。

java 复制代码
package testgetRule
rule "rule_getRule"
    when
    then
        System.out.println(drools.getRule());
end

6、规则文件编码规范

我们在进行drl类型的规则文件编写时尽量遵循如下规范:

  • 所有的规则文件(.drl)应统一放在一个规定的文件夹中,如:/rules文件夹
  • 书写的每个规则应尽量加上注释。注释要清晰明了,言简意赅
  • 同一类型的对象尽量放在一个规则文件中,如所有Student类型的对象尽量放在一个规则文件中
  • 规则结果部分(RHS)尽量不要有条件语句,如if(...),尽量不要有复杂的逻辑和深层次的嵌套语句
  • 每个规则最好都加上salience属性,明确执行顺序
  • Drools默认dialect为"Java",尽量避免使用dialect "mvel"
相关推荐
风象南4 分钟前
SpringBoot 控制器的动态注册与卸载
java·spring boot·后端
醇醛酸醚酮酯22 分钟前
Qt项目锻炼——TODO清单(二)
开发语言·数据库·qt
jioulongzi27 分钟前
记录一次莫名奇妙的跨域502(badgateway)错误
开发语言·python
我是一只代码狗30 分钟前
springboot中使用线程池
java·spring boot·后端
hello早上好43 分钟前
JDK 代理原理
java·spring boot·spring
PanZonghui1 小时前
Centos项目部署之Java安装与配置
java·linux
向阳@向远方1 小时前
第二章 简单程序设计
开发语言·c++·算法
沉着的码农1 小时前
【设计模式】基于责任链模式的参数校验
java·spring boot·分布式
Mr_Xuhhh2 小时前
信号与槽的总结
java·开发语言·数据库·c++·qt·系统架构
纳兰青华2 小时前
bean注入的过程中,Property of ‘java.util.ArrayList‘ type cannot be injected by ‘List‘
java·开发语言·spring·list