drools规则引擎使用文档

本文详细介绍Drools规则引擎的使用方法,包括规则文件结构、规则体结构、查询语法及类型定义等内容,并提供丰富的示例帮助理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

drools规则引擎使用文档

一、规则文件结构

package

import

function  // Optional

query  // Optional

declare   // Optional

global   // Optional

rule "rule name"
    // Attributes
    when
        // Conditions
    then
        // Actions
end

rule "rule2 name"

...

package

  • package:可选,默认值defaultpkg(行尾;可以省略)

    若当前kbase指定路径下所有drl均未指定package,则为defaultpkg;

    每个drl文件中仅可出现一次,且必须置于其它代码之前。

    注意:package namespace建议与kbase packages目录保持一致,否则在最新版本中无法通过kbase获取package对象。

  • import:可选,自动导入package同名包及java.lang.*下的类;

  • global:可选,一般用于Service服务类的导入,例如emailServicesmsService,甚至是Spring 容器上下文对象applicationContext

  • 依据上图importdeclareglobalfunctionqueryrule位置是可以互换的。

  • 注释部分 ///*...*/,可出现在代码的任何地方,会被编译器忽略。

    示例:

    示例

二、规则体结构

rule "rule_name"
    // Attribute
    // Attribute
    when
        // Conditions
    then
        // Actions
end

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QvYy4GXW-1630918204682)(https://docs.jboss.org/drools/release/7.54.0.Final/drools-docs/html_single/LanguageReference/rule.png)]

1.Attribute

rule attributes

  • ruleflow-groupagenda-group概念已统一,ruleflow-group讲覆盖agenda-group属性。

Since version 6.x the two concepts have been unified, the ruleflow-group name will override the agenda-group.

  • Attribute之间可以使用分割,而非;,可省略)
  • 依据上图salienceenableddate-effectivedate-expiresno-loopagenda-groupactivation-groupdurationtimercalendarauto-focuslock-on-activeruleflow-groupdialect、位置是可以互换的。

示例:

package com.example.drools;

dialect  "mvel"

rule "rule1"
    salience 10
    enabled true
    date-effective "4-Sep-2018"
    date-expires "4-Sep-2022"
    no-loop true
    agenda-group "agenda-group-1"
    activation-group "activation-group-1"
    duration 1000
    timer (cron:0/10 * * * * ? )
//    calendar "* * 0-7,18-23 ? * *"
    auto-focus false
    lock-on-active false
    // 覆盖agenda-group属性值
//    ruleflow-group "ruleflow-group-1"
    // 覆盖包级别方言
    dialect "java"
    when
    then
    System.out.println("rule1");
end

2.Conditions

Pattern

条件部分由0个或多个patterns组成,多个pattern之间使用andornot组成,默认值and;

pattern括号内部由0个或多个constraints约束部分组成,多个constrain可用,分割(,语法上等同于&&,但优先级小于&&和||);

  • from和entry-point

from和entry-point一起使用,实现eval时载入数据;

rule "Authorize withdrawal"
  when
    WithdrawRequest( $ai : accountId, $am : amount ) from entry-point "ATM Stream"
    CheckingAccount( accountId == $ai, balance > $am )
  then
    // Authorize withdrawal.
end
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.EntryPoint;

// Create your KIE base and KIE session as usual:
KieSession session = ...

// Create a reference to the entry point:
EntryPoint atmStream = session.getEntryPoint("ATM Stream");

// Start inserting your facts into the entry point:
atmStream.insert(aWithdrawRequest);
  • accumulate

自定义聚合函数导入

import accumulate AverageAccumulateFunction.AverageData average

rule "Average profit"
  when
    $order : Order()
    accumulate( OrderItem( order == $order, $cost : cost, $price : price );
                $avgProfit : average( 1 - $cost / $price ) )
  then
    // Average profit for `$order` is `$avgProfit`.
end

3.Actions

  • 数据操作类

actions包括setmodifyupdateinsertLogicaldelete

  • drools内部变量调用,droolskcontext
rule "rule2"
    when
    then
    System.out.println(drools.getRule().getName());
    System.out.println(kcontext.getKieRuntime().getEnvironment());
end

三、Query语法

![query](https://img-blog.csdnimg.cn/img_convert/7cdf82c54ac3ffbbcc3f528b13a8341c.png)

说明:Query支持可选参数集合,每一个参数都有可选的类型。如果没有指定类型,则默认为Object类型。,支持Query间嵌套调用;LHSRule中的LHS语法一致代表Pattern;Query为了更加紧凑的代码风格,增加了对positional syntax位置语法的支持。

1.基本查询

  • 无参
query "people under the age of 21"
    $person : Person( age < 21 )
end
  • 有参
query contains(String $s, String $c)
    $s := String( this.contains( $c ) )
end

说明: :=pattern with unification; 虽然drools不允许重复声明"绑定",但是支持跨多个属性的参数统一。

示例:

declare PersonFact
    firstName : String @position( 1 )
    lastName : String @position( 0 )
    age : int @position( 2 )
    id : int @position( 3 )
    occupation: String
end

rule "rule2"
when
    // 约束1 限定firstName和lastName;约束2 限定age范围;二者使用id统一参数声明内连接
    PersonFact("cube", $b:"jack"; $a: age, $id:= id)
    PersonFact(age<10, $id:= id)
then
 System.out.println($a);
end

pattern with unification

2.位置语法

positional syntax位置语法用于简化LHS部分代码;可混合使用常规语法命名语法,两者使用;分割,但是位置语法必须放于前;

Location类型为例:

declare Location
    thing : String
    location : String
end
  • Pattern示例-正确
Location(thing == x, location == y)
Location(x; location == y)
Location(x, y;) // x-代表position为0的字段即thing y-代表position为1的字段即location
Location(x; $p:location == y) // $p-代表patternBinding参数
Location(x; $p:location) // 同上
Location(x, $p;) // 同上
  • Pattern示例-错误
Location(thing == x, y;)
Location(thing == x; y;)

四、类型定义与注解

类型声明

事实类型元数据可描述在类级别和字段级别,语法格式为 @key(value),例如@position(0)

1.类型定义

  • 无元数据描述信息
import java.util.Date

declare Person
    name : String
    dateOfBirth : Date
    address : Address
end
  • 有元数据描述信息
import java.util.Date

declare Person
    @author( Bob )
    @dateOfCreation( 01-Feb-2009 )

    name : String @key @maxLength( 30 )
    dateOfBirth : Date
    address : Address
end

2.预定义的元数据标签

元数据作用域可选值默认值描述
@roleclassfact,eventfact该标记决定在复杂事件处理期间,给定的事实类型是作为常规事实对象处理还是作为Drools引擎中的事件对象处理。
@timestampclasssession clock 或自定义时间戳属性(可为attribute)session clock支持参数:会话时钟时间或自定义时间戳属性
@durationclass时间间隔或时间点(可为attribute)Null (zero)该标记决定Drools引擎中事件的持续时间
@expiresclass[#d][#h][#m][#s][[ms]]Null (默认时间不在匹配和激活时过期)此标记决定事件在Drools引擎的工作内存中过期之前的时间。默认情况下,当事件不再匹配和激活任何当前规则时,该事件将过期。您可以定义事件过期的时间。这个标记定义还覆盖了根据时间约束和KIE基中的滑动窗口计算的隐式过期偏移量。只有当Drools引擎以流模式运行时,此标记才可用。
@typesafeclasstrue,falsetrue该标记决定给定的事实类型是否使用类型安全进行编译。
@serialVersionUIDclassintegerNull序列化ID,考虑到兼容性建议在相关类或DRL文件类型声明过程中显式指定serialVersionUID(若未指定则根据类各方面特征自动计算)。
@keyattribute--参与计算equals()hashCode()的属性;同时Drools引擎会隐式地定义3个构造函数,分别为无参构造器、全参构造器、附带@key属性的构造器。
@positionattributeintegerNone优先级原则:子类>父类;显式指定>未指定;声明顺序
@classReactiveclass--全局开关处于开启状态(默认 ALWAYS),代表属性响应性生效;可以通过该标记禁用指定类的属性响应性,实现微调;ALLOWED对应,每次触发规则时重新评估事实的所有事实模式
@propertyReactiveclass--全局开关处于可选状态(ALLOWED)时,代表属性响应性停用;可以通过该标记启用指定类的属性响应性,实现微调;ALWAYS对应,仅对给定模式内受约束或绑定的修改属性做出反应。DISABLED状态时,所有属性更改侦听器都将被忽略(即不重新评估)。
@watchfactPatternProperty name, * (all), ! (not), !* (no properties)None全局开关处于开启状态(ALWAYS)或处于可选状态(ALLOWED)且类被标记为@propertyReactive时,总之,当前类型处于属性响应性状态时,你可以使用通配符或非操作过滤属性;处于非属性响应性,使用@watch或出现冲突例如@watch( firstName, ! firstName ))时编译错误
@propertyChangeSupportclass--增加该标记,可使drools可以监听javabean的属性变动。

下面以典型的电信领域语音呼叫为例

public class VoiceCall {
  private String  originNumber;
  private String  destinationNumber;
  private Date    callDateTime;
  private long    callDuration;  // in milliseconds

  // Constructors, getters, and setters
}
  • 类级别元数据
declare VoiceCall
  @role( event )
  @timestamp( callDateTime )
  @duration( callDuration )
  @expires( 1h35m )
  @typesafe( false )
  @serialVersionUID( 42 )
end
  • @key
declare Person
    firstName : String @key
    lastName : String @key
    age : int
end
  • @position
declare Person
    firstName : String @position( 1 )
    lastName : String @position( 0 )
    age : int @position( 2 )
    occupation: String
end

declare Student extends Person
    degree : String @position( 1 )
    school : String @position( 0 )
    graduationDate : Date
end
  • @watch
// Listens for changes in both `firstName` (inferred) and `lastName`:
Person(firstName == $expectedFirstName) @watch( lastName )

// Listens for changes in all properties of the `Person` fact:
Person(firstName == $expectedFirstName) @watch( * )

// Listens for changes in `lastName` and explicitly excludes changes in `firstName`:
Person(firstName == $expectedFirstName) @watch( lastName, !firstName )

// Listens for changes in all properties of the `Person` fact except `age`:
Person(firstName == $expectedFirstName) @watch( *, !age )

// Excludes changes in all properties of the `Person` fact (equivalent to using `@classReactivity` tag):
Person(firstName == $expectedFirstName) @watch( !* )
  • @propertyChangeSupport
declare Person
    @propertyChangeSupport
end

3.java中使用声明的FactType

import java.util.Date;

import org.kie.api.definition.type.FactType;
import org.kie.api.KieBase;
import org.kie.api.runtime.KieSession;

...

// Get a reference to a KIE base with the declared type:
KieBase kbase = ...

// Get the declared fact type:
FactType personType = kbase.getFactType("org.drools.examples", "Person");

// Create instances:
Object bob = personType.newInstance();

// Set attribute values:
personType.set(bob, "name", "Bob" );
personType.set(bob, "dateOfBirth", new Date());
personType.set(bob, "address", new Address("King's Road","London","404"));

// Insert the fact into a KIE session:
KieSession ksession = ...
ksession.insert(bob);
ksession.fireAllRules();

// Read attributes:
String name = (String) personType.get(bob, "name");
Date date = (Date) personType.get(bob, "dateOfBirth");

Tips:

a.实际使用过程中,可使用Map简化操作

org.kie.api.definition.type.FactType#setFromMap

org.kie.api.definition.type.FactType#getAsMap

b.尽管API的行为类似于Java反射,但API并不使用反射,而是依赖于使用生成的字节码实现的性能更好的访问器

参考:

drools官方文档

未完待续……

第一章 规则引擎初步了解 5 1 为什么会有规则引擎? 5 2 什么是规则引擎? 5 3 为何要使用规则引擎? 6 3.1 声明式编程 6 3.2逻辑与数据分离 6 3.3 速度及可测量性 6 3.4 知识集中化 6 3.5 工具集成 6 3.6 解释机制 6 3.7易懂的规则 7 4 何时应当使用规则引擎? 7 5 如何使用规则引擎? 7 6 何时不要使用规则引擎 ? 8 7 规则引擎的架构和推理 8 8规则引擎的算法 10 9 Java规则引擎商业产品 10 10 Dools介绍 11 第二章. Drools 规则引擎 11 2.1. 概述 11 2.2. 编制 13 2.3. RuleBase 18 2.4. WorkingMemory 和有状态/无状态Sessions 22 2.5. StatefulSession 28 2.6. StatelessSession 29 2.7. Agenda 31 2.8. Truth Maintenance with Logical Objects 34 2.9. 事件模型(Event Model) 37 2.10. 顺序模式 41 第三章. 安装和设置(Core 与IDE) 42 3.1. 安装和使用 42 3.1.1. 依赖库 42 3.1.2. 运行时(Runtime) 43 3.1.3. 安装IDE (规则工作台) 43 3.2. 从源码进行安装 54 3.3. 源码Checkout 54 3.4. 构建 59 3.4.1. 构建源码 59 3.4.2. 构建使用手册 61 3.5. Eclipse 65 3.5.1. 产生Eclipse项目 65 3.5.2. 导入Eclipse项目 66 3.5.3. 导出IDE插件 71 3.5.4. 构建更新站点 76 第四章. 决策表 78 4.1. 在电子表格中的决策表 78 4.1.1. 何时使用决策表 78 4.1.2. 概述 79 4.1.3. 决策表如何工作 81 4.1.4. 关键字和语法 83 4.1.5. 基于决策表建立并集成电子表格 87 4.1.6. 在决策表中管理业务规则 88 第五章. 规则工作台 (IDE) 89 5.1. Introduction 89 5.1.1. 特性概要 90 5.1.2. 建立规则项目 90 5.1.3. 新建规则向导 92 5.1.4. 规则编辑器 94 5.1.5. 视图 95 5.1.6. 领域规范语言DSL 98 5.1.7. The Rete视图 100 5.1.8. 大容量DRL文件 101 5.1.9. 调试规则 102 第六章. 规则语言 103 6.1. 概述 103 6.1.1. 规则文件 103 6.1.2. 规则的构成 104 6.1.3. 保留字 104 6.2. Comments注释 106 6.2.1. 单行注释 106 6.2.2. 多行注释 106 6.3. Package 107 6.3.1. import 108 6.3.2. expander 108 6.3.3. global全局变量 108 6.4. Function 110 6.5. Rule 111 6.5.1. Rule 属性 112 6.5.2. LHS (when) 条件元素 115 6.5.3. The Right Hand Side (then) 140 6.5.4. 对自动封箱/拆箱以及元数据类型的注解 141 6.6. Query 141 6.7. Domain Specific Languages 领域特定语言 142 6.7.1. 何时使用DSL 142 6.7.2. 编辑与管理DSL 143 6.7.3. 在规则使用DSL 144 6.7.4. 增加对fact的约束 145 6.7.5. DSL如何工作 146 6.7.6. 从头开始建立DSL 146 6.8. 规则流 147 6.8.1. 设置规则所属的规则流组 148 6.8.2. 简单的规则流 148 6.8.3. 如何建立规则流 148 6.8.4. 在你的应用程序中使用规则流 153 6.9. XML规则语言 153 6.9.1. 何时使用XML 153 6.9.2. XML 格式 154 6.9.3. 遗留的Drools 2.x XML 规则格式 159 6.9.4. Automatic transforming between formats (XML and DRL) 159 第七章:部署和测试 160 7.1. 部署选项 160 7.1.1. 使用RuleAgent部署 160 7.1.2. 使用drl源码部署 161 7.1.3. 在你的classpath中部署规则 161 7.1.4. 可部署的对象RuleBase, Package等等. 161 7.1.5. 部署模式 163 7.1.6. Web Services 166 7.1.7. 未来的构想 166 7.2. 测试 166 7.2.1. 测试框架 166 7.2.2. FIT for Rules – 一种规则测试框架 166 第八章. BRMS (业务规则管理系统) 168 8.1. 简介 168 8.1.1. 什么是BRMS? 169 8.1.2. 特性概要 170 8.2. 管理指南 170 8.2.1. 安装 171 8.2.2. 数据库配置 172 8.2.3. 安全性 173 8.2.4. 数据管理 176 8.3. 体系结构 178 8.3.1. 从源码构建 179 8.3.2. 可重用组件 180 8.3.3. 版本和存储库 180 8.3.4. 贡献 181 8.4. 快速使用指南 181 8.4.1. 快速使用指南 181 8.4.2. BRMS 概念 183 8.4.3. The business user perspective 197 8.4.4. 部署: 将规则与你的应用集成 197 8.5. 例子与教程 200 8.5.1. 保险经济折扣 200 第九章. Java规则引擎API 202 9.1 简介 202 9.2 java规则引擎API体系结构 202 9.3 规则管理API 202 9.4 运行时API 203 9.5 java规则引擎API的安全问题 204 9.6 异常与日志 205 9.7 JSR小结 205 9.8 Dools API 参考 205 9.8.1 简介 205 9.8.2. 如何使用 205 9.8.3. 参考书目 209
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值