参考文献

Drools基础概念

  • 规则引擎构成
    • Working Memory 工作内存
    • Rule Base 规则库
    • Inference Engine 推理引擎
      • Pattern Matcher 匹配器
      • Agenda 议程
      • Execution Engine 执行引擎
  • Working Memory 工作内存: Drools规则引擎会从Working Memory中获取数据并和规则文件中定义的规则进行模式匹配,所以开发的应用程序只需要将数据Fact插入到Working Memory中即可.
  • Fact事实: 是指在Drools规则应用当中,将一个普通的JavaBean插入到Working Memory后的对象就是Fact对象,Fact对象是我们的应用和规则引擎进行数据交互的桥梁或通道.
  • Rule Base: 规则库,在规则文件中定义的规则都会被加载到规则库中.
  • Pattern Matcher: 匹配器,将Rule Base中的所有规则与Working Memory中的Fact对象进行模式匹配,匹配成功的规则将被激活并放入Agenda中.
  • Agenda: 议程,用于存放通过匹配器进行模式匹配后被激活的规则.
  • Execution Engine: 执行引擎,执行Agenda中被激活的规则.

规则引擎执行过程

  1. 将初始数据(Fact)输入至工作内存(Working Memory)
  2. 使用Pattern Matcher 将规则库中的规则(Rule)和数据(Fact)比较
  3. 如果执行规则存在冲突(Conflict),即同时激活了多个规则,将冲突的规则放入冲突集合
  4. 解决冲突,将激活的规则按顺序放入Agenda
  5. 执行Agenda中的规则.重复步骤2至5,直到执行完毕Agenda中所有规则

KieContainer 生命周期

Drools语法

规则文件

  • 在使用Drools时非常重要的一个工作就是编写规则文件,通常规则文件的后缀为.drl.drlDrools Rule Language的缩写
关键字 描述
package 包名,只限于逻辑上的管理,同一个包名下的查询或者函数可以直接调用
import 用于导入类或者静态方法
global 全局变量
function 自定义函数
query 查询
rule end 规则体

规则体语法结构

  • 规则体是规则文件内容中的重要组成部分,是进行业务规则判断、处理业务结果的部分.

    1
    2
    3
    4
    5
    6
    7
    rule "ruleName"
    attributes
    when
    LHS
    then
    RHS
    end
  • rule : 关键字,表示规则开始,参数为规则的唯一名称

  • attributes: 规则属性,是rulewhen之间的参数,为可选项

  • when: 关键字,后面跟规则的条件部分

  • LHS(Left Hand Side): 是规则的条件部分的通用名称.它是由零个或多个条件元素组成.如果LHS为空,则它将被始终视为true的条件元素.

  • then: 关键字,后面跟规则的结果部分.

  • RHS(Right Hand Side): 是规则的后果或行动部分的通用名称.

  • end: 关键字,表是一个规则结束

Pattern模式匹配

  • LHS部分由一个或者多个条件组成,条件又称为Pattern.

  • Pattern的语法结构为: 绑定变量名:Object(Field约束)

    1
    2
    3
    4
    5
    rule "rule1"
    when
    $var:Student()
    then
    end
    • 其中绑定变量名可以省略,通常绑定变量名的命名一般建议以$开始.如果定义了绑定变量名,就可以在规则提RHS部分使用绑定的变量名来操作相应的Fact对象.Field约束部分是需要返回true或者false的零个或多个表达式.

    • 绑定变量既可以用在对象上,也可以用在对象的属性上.

      1
      2
      3
      4
      5
      rule "rule1"
      when
      $s:Student($name:name)
      then
      end
    • LHS部分还可以定义多个Pattern,多个Pattern之间可以使用and或者or进行连接,也可以不写,默认连接为and.

比较操作符

符号 说明
> 大于
< 小于
>= 大于等于
<= 小于等于
== 等于
!= 不等于
contains 检查一个Fact对象的某个属性值是否包含一个指定的对象值
not contains 检查一个Fact对象的某个属性值是否不包含一个指定的对象值
memberOf 判断一个Fact对象的某个属性是否在一个或多个集合中
not memberOf 判断一个Fact对象的某个属性是否不在一个或多个集合中
matches 判断一个Fact对象的属性是否与提供的标准的Java正则表达式进行匹配
not matches 判断一个Fact对象的属性是否不与提供的标准的Java正则表达式进行匹配
1
2
3
4
5
6
7
8
9
10
11
// contains | not contains语法结构
Object(Field[Collection/Array] contains value)
Object(Field[Collection/Array] not contains value)

// memberOf | not memberOf语法结构
Object(field memberOf value[Collection/Array])
Object(field not memberOf value[Collection/Array])

// matches | not matches语法结构
Object(field matches "正则表达式")
Object(field not matches "正则表达式")

执行指定规则

  • 在调用规则代码时,满足条件的规则都会被执行.只想执行其中的某个规则,可以通过规则过滤器来实现执行指定规则.对于规则文件不用做任何修改,只需要修改Java代码即可.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
     KieServices kieServices = KieServices.Factory.get();
    KieContainer kieClasspathContainer = kieServices.getKieClasspathContainer();
    //会话对象,用于和规则引擎交互
    KieSession kieSession = kieClasspathContainer.newKieSession();

    ArrayList commonIpList = new ArrayList<>();
    commonIpList.add("19.11.111.12");
    commonIpList.add("19.11.111.13");
    commonIpList.add("19.11.111.14");
    commonIpList.add("19.11.111.15");
    commonIpList.add("19.11.111.16");

    LoginSucceededEvent event = new LoginSucceededEvent();
    event.setSourceIp("19.11.111.11");
    event.setCommonIpList(commonIpList);

    kieSession.setGlobal("alertService",new AlertService())
    //将数据提供给规则引擎,规则引擎会根据提供的数据进行规则匹配
    kieSession.insert(event);

    //激活规则引擎,如果规则匹配成功则执行规则
    kieSession.fireAllRules(new RuleNameEqualsAgendaFilter("abnormal_ip_detection"));
    //关闭会话
    kieSession.dispose();

关键字

  • Drools的关键字分为: 硬关键字(Hard keywords)和软关键字(Soft keywords).
    • 硬关键字是我们在规则文件中定义包名或者规则名时明确不能使用的,否则程序会报错.软关键字虽然可以使用,但是不建议使用.
  • 硬关键字: true false null
  • 软关键字: lock-on-active date-effective date-expires no-loop auto-focus activation-group agenda-group ruleflow-group entry-point duration package import dialect salience enabled attributes rule extend when then template query declare function global eval not in or and exists forall accumulate collect from action reverse result end over init

Drools内置方法

  • 规则文件的RHS部分的主要作用是通过插入,删除或修改工作内存中的Fact数据,来达到控制规则引擎执行的目的.
  • Drools提供了一些方法可以用来操作工作内存中的数据,**操作完成后规则引擎会重新进行相关规则的匹配,**原来没有匹配成功的规则在我们修改数据完成后有可能就会匹配成功了.
update方法
  • update方法的作用是更新工作内存中的数据,并让相关的规则重新匹配. (要注意避免死循环)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    package student
    import com.itheima.drools.entity.Student

    /*
    当前规则文件用于测试Drools提供的内置方法
    */

    rule "rule_student_age小于10岁"
    when
    $s:Student(age < 10)
    then
    $s.setAge(15);
    update($s);//更新数据,导致相关的规则会重新匹配
    System.out.println("规则rule_student_age小于10岁触发");
    end
insert方法
  • insert方法的作用是向工作内存中插入数据,并让相关的规则重新匹配.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    package student
    import com.itheima.drools.entity.Student

    /*
    当前规则文件用于测试Drools提供的内置方法
    */

    rule "rule_student_age等于10岁"
    when
    $s:Student(age == 10)
    then
    Student student = new Student();
    student.setAge(5);
    insert(student);//插入数据,导致相关的规则会重新匹配
    System.out.println("规则rule_student_age等于10岁触发");
    end
retract方法
  • retract方法的作用是删除工作内存中的数据,并让相关的规则重新匹配.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    package student
    import com.itheima.drools.entity.Student

    /*
    当前规则文件用于测试Drools提供的内置方法
    */

    rule "rule_student_age等于10岁时删除数据"
    /*
    salience: 设置当前规则的执行优先级,数值越大越优先执行,默认值为0.
    因为当前规则的匹配条件和下面规则的匹配条件相同,为了保证先执行当前规则,需要设置优先级
    */
    salience 100
    when
    $s:Student(age == 10)
    then
    retract($s);//retract方法的作用是删除工作内存中的数据,并让相关的规则重新匹配.
    System.out.println("规则rule_student_age等于10岁时删除数据触发");
    end

规则属性

属性名称 说明
enabled 用于指定当前规则是否启用
enabled属性对应取值为truefalse.默认值为true
dialect 用于指定当前规则使用的语言类型,取值为javamvel,默认值为java
salience 用于指定规则的执行优先级,取值类型为Integer.数值越大越优先执行
no-loop no-loop属性用于防止死循环,当规则通过update之类的函数修改了Fact对象时,可能使当前规则再次被激活从而导致死循环.取值类型为Boolean,默认值为false
activation-group activation-group属性为激活分组,具有相同分组名称的规则只能有一个规则被触发.取值类型为String.
agenda-group agenda-group属性为议程分组,属于另一种可控的规则执行方式.用户可通过设置agenda-group来控制规则的执行,只有获取焦点的组中的规则才会被触发.
auto-focus auto-focus属性为自动获取焦点,取值类型为Boolean,默认值为false.一般结合agenda-group属性使用,当一个议程分组未获取焦点时,可以设置auto-focus属性来控制.
timer timer属性可以通过定时器的方式指定规则执行的时间
date-effective date-effective属性用于指定规则的生效时间
data-expires date-expires属性用于指定规则的失效时间
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// 基础格式
rule "ruleName"
attributes
when
LHS
then
RHS
end

//
dialect "java"
rule "ruleName"
// 指定当前规则不可用,当前规则无论是否匹配成功都不会执行
enabled fasle
// 设置执行优先级
salience 9
// 防止死循环
no-loop true
// 激活分组
activation-group "activation-group"
// 议程分组
agenda-group "agenda-group"
// 自动获取焦点
auto-focus true
// timer (int: <initial delay> <repeat interval>?)
// 5秒后触发,然后每隔2秒触发一次
timer(5s 2s)
// timer(cron: <cron expression>)
// 每隔1秒触发一次
timer(cron: 0/1 * * * * ?)
// 指定规则的生效时间 默认日期格式为: dd-MMM-yyyy
date-effective "2020-10-01 10:00"
// 指定规则的失效时间
date-expires "2019-10-01 10:00"
when
LHS
then
RHS
end

LHS加强

复合值限制in/not in

  • 复合值限制是指超过一种匹配值的限制条件,类似于SQL语句中的in关键字.Drools规则体中的LHS部分可以使用in或者not in进行复合值的匹配
1
2
3
// Object(field in (比较值1,比较值2...))
$s:Student(name in ("张三","李四","王五"))
$s:Student(name not in ("张三","李四","王五"))

条件元素eval

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

    1
    2
    3
    4
    // eval(表达式)
    eval(true)
    eval(false)
    eval(1 == 1)

条件元素not

  • not用于判断Working Memory中是否存在某个Fact对象,如果不存在则返回true,如果存在则返回false

    1
    2
    3
    // not Object(可选属性约束)
    not Student()
    not Student(age < 10)

条件元素exists

  • exists的作用与not相反,用于判断Working Memory中是否存在某个Fact对象,如果存在则返回true,不存在则返回false.

    1
    2
    3
    // exists Object(可选属性约束)
    exists Student()
    exists Student(age < 10 && name != null)
  • 当向Working Memory中加入多个满足条件的Fact对象时,使用了exists的规则执行一次,不使用exists的规则会执行多次.

规则继承

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    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

RHS加强

halt

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    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

getWorkingMemory

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

    1
    2
    3
    4
    5
    6
    package testgetWorkingMemory
    rule "rule_getWorkingMemory"
    when
    then
    System.out.println(drools.getWorkingMemory());
    end

getRule

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

    1
    2
    3
    4
    5
    6
    package testgetRule
    rule "rule_getRule"
    when
    then
    System.out.println(drools.getRule());
    end

规则文件编码规范

  • 所有的规则文件(.drl)应统一放在一个规定的文件夹中,如:/rules文件夹
  • 书写的每个规则应尽量加上注释。注释要清晰明了,言简意赅
  • 同一类型的对象尽量放在一个规则文件中,如所有Student类型的对象尽量放在一个规则文件中
  • 规则结果部分(RHS)尽量不要有条件语句,如if(...),尽量不要有复杂的逻辑和深层次的嵌套语句
  • 每个规则最好都加上salience属性,明确执行顺序
  • Drools默认dialect"Java",尽量避免使用dialect "mvel"

开发步骤

  • 添加依赖

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    <dependencies>
    <!-- Drools -->
    <dependency>
    <groupId>org.drools</groupId>
    <artifactId>drools-engine</artifactId>
    </dependency>
    </dependencies>
    <dependencyManagement>
    <dependencies>
    <dependency>
    <groupId>org.drools</groupId>
    <artifactId>drools-bom</artifactId>
    <type>pom</type>
    <version>${drools.version}</version>
    <scope>import</scope>
    </dependency>
    </dependencies>
    </dependencyManagement>
  • 编写规则文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    package rules;
    dialect "java"

    import cn.holelin.zeus.events.alert.LoginSucceededEvent;
    import cn.holelin.zeus.enums.EventTypeEnum;

    import cn.holelin.zeus.service.AlertService
    import cn.hutool.json.JSONUtil

    global AlertService alertService;

    // 登录异常检测
    rule "abnormal_ip_detection"
    when
    $event: LoginSucceededEvent(commonIpList != null && sourceIp not memberOf commonIpList && commonIpList.size() >= 5)
    then
    alertService.alert(EventTypeEnum.EVENT_LOGIN_IP_DETECTION, JSONUtil.toJsonStr($event));
    end
  • 使用

    1. 获取KieServices
    2. 获取KieContainer
    3. 获取KieSession
    4. 插入Fact对象
    5. 触发规则
    6. 关闭KieSession
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    @Test
    public void test(){
    KieServices kieServices = KieServices.Factory.get();
    KieContainer kieClasspathContainer = kieServices.getKieClasspathContainer();
    //会话对象,用于和规则引擎交互
    KieSession kieSession = kieClasspathContainer.newKieSession();

    ArrayList commonIpList = new ArrayList<>();
    commonIpList.add("19.11.111.12");
    commonIpList.add("19.11.111.13");
    commonIpList.add("19.11.111.14");
    commonIpList.add("19.11.111.15");
    commonIpList.add("19.11.111.16");

    LoginSucceededEvent event = new LoginSucceededEvent();
    event.setSourceIp("19.11.111.11");
    event.setCommonIpList(commonIpList);

    kieSession.setGlobal("alertService",new AlertService())
    //将数据提供给规则引擎,规则引擎会根据提供的数据进行规则匹配
    kieSession.insert(event);

    //激活规则引擎,如果规则匹配成功则执行规则
    kieSession.fireAllRules();
    //关闭会话
    kieSession.dispose();
    }

Springboot集成Drools

依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<dependencies>
<!-- Drools -->
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-engine</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-bom</artifactId>
<type>pom</type>
<version>${drools.version}</version>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package cn.holelin.zeus.config;


import org.drools.model.codegen.ExecutableModelProject;
import org.kie.api.KieBase;
import org.kie.api.KieBaseConfiguration;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.kie.api.conf.EventProcessingOption;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.KieSessionConfiguration;
import org.kie.api.runtime.conf.ClockTypeOption;
import org.kie.internal.io.ResourceFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;

/**
* @author holelin
*/
@Configuration
public class DroolsConfiguration {

private static final String RULES_PATH = "rules/";

@Bean
@ConditionalOnMissingBean(KieFileSystem.class)
public KieFileSystem kieFileSystem() throws IOException {
KieFileSystem kieFileSystem = getKieServices().newKieFileSystem();
for (Resource file : getRuleFiles()) {
kieFileSystem.write(ResourceFactory.newClassPathResource(RULES_PATH + file.getFilename(), "UTF-8"));
}
return kieFileSystem;
}

private Resource[] getRuleFiles() throws IOException {
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
return resourcePatternResolver.getResources("classpath*:" + RULES_PATH + "**/*.*");
}

@Bean
@ConditionalOnMissingBean(KieContainer.class)
public KieContainer kieContainer() throws IOException {
final KieServices kieServices = getKieServices();
final KieRepository kieRepository = kieServices.getRepository();
kieRepository.addKieModule(kieRepository::getDefaultReleaseId);
KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem());
kieBuilder.buildAll(ExecutableModelProject.class);
return kieServices.newKieContainer(kieRepository.getDefaultReleaseId());
}

private KieServices getKieServices() {
return KieServices.Factory.get();
}

@Bean
@ConditionalOnMissingBean(KieBase.class)
public KieBase kieBase() throws IOException {
final KieServices kieServices = getKieServices();
final KieBaseConfiguration configuration = kieServices.newKieBaseConfiguration();
configuration.setOption(EventProcessingOption.STREAM);
return kieContainer().newKieBase(configuration);
}

}

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package cn.holelin.drools.service;

import org.kie.api.KieBase;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RuleService {
@Autowired
private KieBase kieBase;

public void rule(){
KieSession kieSession = kieBase.newKieSession();
kieSession.fireAllRules();
kieSession.dispose();
}
}