Drools记录之DRL规则语言

二、DRL(Drools规则语言)规则

DRL文件可以包含单个或多个规则,查询和函数,并且可以定义资源声明,例如由规则和查询分配和使用的导入,全局和属性。DRL软件包必须在DRL文件的顶部列出,并且规则通常在最后列出。所有其他DRL组件都可以遵循任何顺序。

每个规则在规则包中必须具有唯一的名称。如果在包中的任何DRL文件中多次使用相同的规则名称,则规则将无法编译。始终用双引号(rule “rule name”)括住规则名称,以防止可能的编译错误,尤其是在规则名称中使用空格的情况下。

与DRL规则相关的所有数据对象必须与Business Central中的DRL文件位于同一项目包中。默认情况下,导入同一包中的资源。可以使用DRL规则导入其他软件包中的现有资源。

1、DRL中的包名定义

包是Drools中相关资产的文件夹,例如数据对象,DRL文件,决策表和其他资产类型。包还充当每组规则的唯一名称空间。一个规则库可以包含多个程序包。通常,将包的所有规则与包声明存储在同一文件中,以便包是独立的。但是,您可以从要在规则中使用的其他包中导入对象。

示例:

package org.mortgages;

请注意,

  • 程序包必须具有名称空间,并使用标准Java约定来声明程序包名称,即,没有空格。
  • 必须在文件的顶部,且分号是可选的。

2、DRL中的导入语句

与Java中的import语句类似,可以使用格式指定包和数据对象packageName.objectName,Drools引擎自动从Java包中导入与DRL文件中的导入语句同名的类,java.lang自动导入。

示例:

import org.mortgages.LoanApplication;

3、DRL中的function(方法函数定义)

DRL文件中的函数将语义代码放入规则源文件中,而不是Java类中。在then后面重复使用的重复方法,可定义function来避免代码冗余。在DRL文件中的规则上方,您可以声明函数或从帮助程序类中导入静态方法作为函数,然后then在规则的action()部分中按名称使用该函数。

带有规则的示例函数声明(选项1)

function String hello(String applicantName) {
    return "Hello " + applicantName + "!";
}

rule "Using a function"
  when
    // Empty
  then
    System.out.println( hello( "James" ) );
end

带有规则的示例函数导入(选项2)

import function my.package.applicant.hello;

rule "Using a function"
  when
    // Empty
  then
    System.out.println( hello( "James" ) );
end

4、DRL中的查询(query)

DRL文件中的查询在Drools引擎的工作内存中搜索与DRL文件中的规则相关的事实。
在DRL文件中添加查询定义,然后在应用程序代码中获得匹配的结果。查询搜索一组已定义的条件,不需要when或没有指定then。
要求query的名称必须唯一,因为是全局的。
可以在DRL文件中的规则上方定义查询和查询结果参数。

DRL文件中的示例查询定义

query "people under the age of 21"
    $person : Person( age < 21 )
end

获取查询结果的示例应用程序代码

QueryResults results = ksession.getQueryResults( "people under the age of 21" );
System.out.println( "we have " + results.size() + " people under the age  of 21" );

获取和迭代查询结果的示例应用程序代码

QueryResults results = ksession.getQueryResults( "people under the age of 21" );
System.out.println( "we have " + results.size() + " people under the age of 21" );

System.out.println( "These people are under the age of 21:" );

for ( QueryResultsRow row : results ) {
    Person person = ( Person ) row.get( "person" );
    System.out.println( person.getName() + "\n" );
}

5、DRL中的类型声明和元数据

当声明新的fact类型时,Drools引擎在编译时会生成一个表示该fact类型的Java类。生成的Java类是类型定义的一对一JavaBeans映射。

(1)DRL中没有元数据的类型声明

使用规则声明新事实类型的示例

declare Person
  name : String
  dateOfBirth : java.util.Date
  address : Address
end

rule "Using a declared type"
  when
    $p : Person( name == "James" )
  then   // Insert Mark, who is a customer of James.
    Person mark = new Person();
    mark.setName( "Mark" );
    insert( mark );
end

在这个例子中,新的fact类型Person有三个属性name,dateOfBirth和address。每个属性的类型都可以是任何有效的Java类型,包括创建的另一个类或先前声明的fact类型。该dateOfBirth属性具有java.util.DateJava API中的类型,并且该address属性具有先前定义的fact类型Address。

为了避免在每次声明类时都写出全限定名,可以将全称定义为import子句的一部分:

import java.util.Date

declare Person
    name : String
    dateOfBirth : Date
    address : Address
end

为Person事实类型声明生成的Java类

public class Person implements Serializable {
    private String name;
    private java.util.Date dateOfBirth;
    private Address address;

    // Empty constructor
    public Person() {...}

    // Constructor with all fields
    public Person( String name, Date dateOfBirth, Address address ) {...}

    // If keys are defined, constructor with keys
    public Person( ...keys... ) {...}

    // Getters and setters
    // `equals` and `hashCode`
    // `toString`
}

使用声明的Person事实类型的示例规则

rule "Using a declared type"
  when
    $p : Person( name == "James" )
  then   // Insert Mark, who is a customer of James.
    Person mark = new Person();
    mark.setName( "Mark" );
    insert( mark );
end

(2)DRL中的枚举类型声明

带有调度规则的示例枚举类型声明

declare enum DaysOfWeek
   SUN("Sunday"),MON("Monday"),TUE("Tuesday"),WED("Wednesday"),THU("Thursday"),FRI("Friday"),SAT("Saturday");
   fullName : String
end

rule "Using a declared Enum"
when
   $emp : Employee( dayOff == DaysOfWeek.MONDAY )
then
   ...
end

(3)DRL中的扩展类型声明

扩展类型声明示例

import org.people.Person

declare Person end

declare Student extends Person
    school : String
end

declare LongTermStudent extends Student
    years : int
    course : String
end

(4)DRL中带有元数据的类型声明

在下面的例子中,两个元数据属性@author和@dateOfCreation被声明为Person事实类型,以及两个元数据项@key和@maxLength被声明为name属性。的@key元数据属性不具有所需的值,因此括号和值被省略。

import java.util.Date

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

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

导入类型的示例元数据声明

import org.drools.examples.Person

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

声明类型的元数据声明示例

declare org.drools.examples.Person
    @author( Bob )
    @dateOfCreation( 01-Feb-2009 )
end

(5)DRL中事实类型和属性声明的元数据标签

元数据标签说明示例
@role( fact | event )确定在复杂事件处理期间,给定的事实类型是作为
常规事实还是在Drools引擎中的事件处理。
默认参数: fact
支持的参数:fact,event
declare VoiceCall
 @role( event )
end
@timestamp(<attributeName>)自定义时间戳属性。
默认参数: Drools引擎会话时钟增加的时间
支持的参数:会话时钟时间或自定义时间戳属性
declare VoiceCall
 @role( event )
 @timestamp( callDateTime )
end
@duration( <attributeName> )该标签确定Drools引擎中事件的持续时间。
事件可以是基于时间间隔的事件或时间点事件。
基于时间间隔的事件具有持续时间,并持续存在于Drools引擎
的工作存储器中,直到其持续时间过去。
默认参数: 空(零)
支持的参数:自定义工期属性
declare VoiceCall
 @role( event )
 @duration( callDuration )
end
@expires( <timeOffset> )该标签确定事件在Drools引擎的工作内存中过期之前的持续时间。
当Drools引擎以流模式运行时,此标签才可用。
默认参数: Null(事件在事件无法匹配和激活规则后过期)
支持的参数:timeOffset格式的自定义属性[#d][#h][#m][#s][[ms]]
declare VoiceCall
 @role( event )
 @expires( 1h35m )
end
@typesafe( <boolean> )确定是否使用类型安全性编译给定的事实类型。
默认参数: true
支持的参数:true,false
declare VoiceCall
 @role( event )
 @typesafe( false )
end
@serialVersionUID(<integer>)类序列化。
默认参数: 空
支持的参数:自定义serialVersionUID整数
declare VoiceCall
 @serialVersionUID( 42 )
end
<attributeDefinition> @key生成的类的键标识符,会自动实现equals()和hashCode()方法,
以确定该类型的两个实例是否彼此相等。–详细请转到表格下方(附1)
默认参数: 无
支持的参数:无
declare VoiceCall
 firstName : String @key
 lastName : String @key
 age : int
end
<attributeDefinition> @position ( <integer> )标注定义的类的属性顺序,如果未加@position的话则放到最后,
示例中的顺序为lastName-firstName-age-occupation。
–详细请转到表格下方(附2)
默认参数: 无
支持的参数:任何整数
declare VoiceCall
 firstName : String @position( 1 )
 lastName : String @position( 0 )
 age : int @position( 2 )
 occupation: String
end

附1
Drools引擎检查firstName和lastName属性以确定两个的实例是否Person彼此相等,但不检查该age属性。Drools引擎还隐式生成三个构造函数:一个没有参数,一个带有@key字段,一个带有所有字段的构造函数:

Person() // Empty constructor
Person( String firstName, String lastName )
Person( String firstName, String lastName, int age )
//可以基于键构造函数创建该类型的实例
Person person = new Person( "John", "Doe" );

附2
在位置参数中,不需要指定字段名称,因为位置映射到已知的命名字段。例如,参数Person( lastName == “Doe” )与相同Person( “Doe”; ),其中该lastName字段在DRL声明中具有最高位置注释。分号;表示之前的所有内容都是位置参数。您可以使用分号将模式中的位置参数和命名参数分开,以将它们分开。位置参数中尚未绑定的所有变量都将绑定到映射到该位置的字段。

以下示例模式说明了构造位置参数和命名参数的不同方法。模式具有两个约束和一个绑定,分号将位置部分与命名的参数部分区分开。位置参数支持仅使用文字的变量,文字和表达式,但不单独支持变量。

具有位置和命名参数的示例模式

Person( "Doe", "John", $a; )

Person( "Doe", "John"; $a : age )

Person( "Doe"; firstName == "John", $a : age )

Person( lastName == "Doe"; firstName == "John", $a : age )

(6)在应用程序代码中访问DRL声明的类型

通过FactType API处理声明的事实类型的示例应用程序代码

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");

6、DRL中的全局变量

DRL文件中的全局变量通常为规则提供数据或服务,例如规则结果中使用的应用程序服务,并从规则返回数据,例如在规则结果中添加日志或值。可以通过KIE会话配置或REST操作在Drools引擎的工作内存中设置全局值,在DRL文件中的规则上方声明全局变量,然后在规则的action(then)部分中使用它。对于多个全局变量,在DRL文件中要使用单独的行。

Drools引擎的示例全局列表配置

List<String> list = new ArrayList<>();
KieSession kieSession = kiebase.newKieSession();
kieSession.setGlobal( "myGlobalList", list );

带有规则的示例全局变量定义

global java.util.List myGlobalList;

rule "Using a global"
  when
    // Empty
  then
    myGlobalList.add( "My global list" );
end

7、DRL中的规则属性

属性
salience定义规则优先级的整数。在激活队列中排序时,具有较高显着性值的规则将具有较高的优先级。
例: salience 10
enabled布尔值。选择该选项后,将启用规则。如果未选择该选项,则该规则将被禁用。
例: enabled true
date-effective包含日期和时间定义的字符串。仅当当前日期和时间在date-effective属性之后时,才能激活该规则。
例: date-effective “4-Sep-2018”
date-expires包含日期和时间定义的字符串。如果当前日期和时间在date-expires属性之后,则无法激活该规则。
例: date-expires “4-Oct-2018”
no-loop布尔值。选择该选项后,如果规则的结果重新触发了先前满足的条件,则无法重新激活(循环)规则。如果未选择条件,则可以在这些情况下循环规则。
例: no-loop true
agenda-group一个字符串,用于标识您要向其分配规则的议程组。通过议程组,您可以对议程进行分区,以提供对规则组的更多执行控制。只有已获得焦点的议程组中的规则才能被激活。
例: agenda-group “GroupName”
activation-group一个字符串,用于标识您要向其分配规则的激活(或XOR)组。在激活组中,只能激活一个规则。触发的第一个规则将取消激活组中所有规则的所有未决激活。
例: activation-group “GroupName”
duration一个长整数值,定义了如果仍满足规则条件,则可以激活规则的持续时间(以毫秒为单位)。
例: duration 10000
timer一个字符串,用于标识int(间隔)或cron计时器定义以调度规则。
示例:(timer ( cron:* 0/15 * * * ? ) 每15分钟一次)
calendar一个石英调度规则日历定义。
示例:(calendars “* * 0-7,18-23 ? * *” 不包括非营业时间)
auto-focus一个布尔值,仅适用于议程组中的规则。选择该选项后,下次激活该规则时,焦点将自动聚焦到分配了该规则的议程组。
例: auto-focus true
lock-on-active一个布尔值,仅适用于规则流组或议程组中的规则。选择该选项后,下一次该规则的规则流组变为活动状态或该规则的议程组获得焦点时,该规则流组将不再处于活动状态或该议程组失去焦点之前,无法再次激活该规则。这是该no-loop属性的更强版本,因为匹配匹配规则的激活将被忽略,而与更新的来源无关(不仅是规则本身)。此属性是计算规则的理想选择,在计算规则中,您有许多修改事实的规则,并且您不希望任何规则重新匹配并再次触发。
例: lock-on-active true
ruleflow-group标识规则流组的字符串。在规则流组中,只有在相关规则流激活了该组时,规则才能触发。
例: ruleflow-group “GroupName”
dialect一个字符串,用于标识规则中的代码表达式JAVA或MVEL将其用作语言。默认情况下,该规则使用在程序包级别指定的方言。此处指定的任何方言都会覆盖规则的打包方言设置。
例: dialect “JAVA”

8、DRL中的规则条件(when)

when是DRL规则的一部分(也成为LHS Left Hand Side),包含执行操作必须满足的条件。
如果when部分为空,则认为是true,会在findAllRules()时执行then的操作,适用于设置Drools引擎状态。

没有条件的示例规则

rule "Always insert applicant"
  when
    // Empty
  then   // Actions to be executed once
    insert( new Applicant() );
end

// The rule is internally rewritten in the following way:

rule "Always insert applicant"
  when
    eval( true )
  then
    insert( new Applicant() );
end

如果规则条件使用的多个模式,没有定义的关键字连词(如and,or或not),默认结合是and:

没有关键字连接的示例规则

rule "Underage"
  when
    application : LoanApplication()
    Applicant( age < 21 )
  then
    // Actions
end

// The rule is internally rewritten in the following way:

rule "Underage"
  when
    application : LoanApplication()
    and Applicant( age < 21 )
  then
    // Actions
end

(1)模式和约束

模式可以潜在地匹配插入Drools引擎的工作内存中的每个fact。模式还可以包含约束,以进一步定义要匹配的fact。

  • 匹配指定类型的fact,如:Person()

  • 在括号中可添加过滤条件,如:Person(age==18)

  • 类型不一定是某个fact对象的实际类,可以是超类或接口,如:Object()匹配所有fact

  • 约束本质上是Java表达式与一些增强表达式,注意:Person( firstName == “John” )类似于java.util.Objects.equals(person.getFirstName(), “John”)

如下是具有JavaBeans属性的DRL约束语法

Person( age == 50 )

// This is the same as the following getter format:
// 上面的效率要高于下面的

Person( getAge() == 50 )

具有嵌套属性访问的示例模式

Person( address.houseNumber == 50 )

// This is the same as the following format:

Person( getAddress().getHouseNumber() == 50 )
  • 可以使用任何返回boolean值的Java表达式作为模式括号内的约束。Java表达式可以与其他表达式增强功能(例如属性访问)混合使用。

使用属性访问和Java表达式约束的示例模式

Person( age == 50 )

可以使用括号来更改评估优先级,就像在任何逻辑或数学表达式中一样

Person( age > 100 && ( age % 10 == 0 ) )

用Java方法的示例约束

Person( Math.round( weight / ( height * height ) ) < 25.0 )
  • 对于约束组,可以使用定界逗号,来使用隐式and连接语义

具有多个约束的示例模式

// Person is at least 50 years old and weighs at least 80 kilograms:
Person( age > 50, weight > 80 )

// Person is at least 50 years old, weighs at least 80 kilograms, and is taller than 2 meters:
Person( age > 50, weight > 80, height > 2 )

这里要注意的是,虽然逗号和&&语义相同,但执行顺序不同,&&>||>逗号

(2)模式和约束中的绑定变量

可以将变量绑定到模式和约束,以引用规则其他部分中的匹配对象。绑定变量可以更高效或更一致地定义规则,以及如何注释数据模型中的fact。要更轻松地区分规则中的变量和字段,一般采用$variable的标准格式定义变量,尤其是在复杂规则中。虽然有用,但不是必须的。

具有绑定变量的模式

rule "simple rule"
  when
    $p : Person()
  then
    System.out.println( "Person " + $p );
end

同样,也可以将变量绑定到模式约束中的属性

// Two persons of the same age:
Person( $firstAge : age ) // Binding
Person( age == $firstAge ) // Constraint expression

(3)嵌套约束和内联强制转换

访问多个属性的示例模式

Person( name == "mark", address.city == "london", address.country == "uk" )
//the same as 
Person( name == "mark", address.( city == "london", country == "uk") )

可以使用语法#将其对象转换为子类型

内联强制转换为子类型的示例模式

// Inline casting with subtype name:
Person( name == "mark", address#LongAddress.country == "uk" )

// Inline casting with fully qualified class name:
Person( name == "mark", address#org.domain.LongAddress.country == "uk" )

// Multiple inline casts:
Person( name == "mark", address#LongAddress.country#DetailedCountry.population > 10000000 )

可以使用instanceof运算符来推断该类型字段的后续使用以及模式,如下例所示

Person( name == "mark", address instanceof LongAddress, address.country == "uk" )

(4)约束中的日期文字

Drools引擎支持date格式dd-mmm-yyyy。

具有日期文字限制的示例模式

Person( bornBefore < "27-Oct-2009" )

(5)约束中的日期文字

  • .(), #

示例

// Inline casting with subtype name:
Person( name == "mark", address#LongAddress.country == "uk" )

// Inline casting with fully qualified class name:
Person( name == "mark", address#org.domain.LongAddress.country == "uk" )

// Multiple inline casts:
Person( name == "mark", address#LongAddress.country#DetailedCountry.population > 10000000 )
  • !. (等同于 ! = null )

具有空安全解引用的约束示例

Person( $streetName : address!.street )

// This is internally rewritten in the following way:

Person( address != null, $streetName : address.street )
  • [] (使用此运算符可按List索引访问值或Map按键访问值。)

List和Map访问的示例约束

// The following format is the same as `childList(0).getAge() == 18`:
Person(childList[0].age == 18)

// The following format is the same as `credentialMap.get("jdoe").isValid()`:
Person(credentialMap["jdoe"].valid)
  • <,<=,>,>=

before运算符的示例约束

Person( birthDate < $otherBirthDate )

Person( firstName < $otherFirstName )
  • ==, !=

具有null安全相等性的约束示例

Person( firstName == "John" )

// This is similar to the following formats:

java.util.Objects.equals(person.getFirstName(), "John")
"John".equals(person.getFirstName())
  • &&, || (这些运算符可以创建一个简化的组合关系条件)

具有简化组合关系的示例约束

// Simple abbreviated combined relation condition using a single `&&`:
Person(age > 30 && < 40)

// Complex abbreviated combined relation using groupings:
Person(age ((> 30 && < 40) || (> 20 && < 25)))

// Mixing abbreviated combined relation with constraint connectives:
Person(age > 30 && < 40 || location == "london")
  • matches, not matches (可以指示字段与指定的Java正则表达式匹配或不匹配)

匹配或不匹配正则表达式的示例约束

Person( country matches "(USA)?\\S*UK" )

Person( country not matches "(USA)?\\S*UK" )
  • contains, not contains (可以验证Array或字段是否Collection包含或不包含指定值)

用实施例的限制contains,并not contains为集合

// Collection with a specified field:
FamilyTree( countries contains "UK" )

FamilyTree( countries not contains "UK" )


// Collection with a variable:
FamilyTree( countries contains $var )

FamilyTree( countries not contains $var )
  • memberOf, not memberOf (可验证字段是否为定义为变量的Array或的成员Collection)

用实施例的限制memberOf,并not memberOf与收集

FamilyTree( person memberOf $europeanDescendants )

FamilyTree( person not memberOf $europeanDescendants )
  • str (可以验证String以指定值开头或结尾的字段,也包括长度)

约束示例 str

// Verify what the String starts with:
Message( routingValue str[startsWith] "R1" )

// Verify what the String ends with:
Message( routingValue str[endsWith] "R2" )

// Verify the length of the String:
Message( routingValue str[length] 17 )
  • in, notin (可以指定一个以上的可能值来匹配约束(复合值限制))

用实施例的约束in和notin

Person( $color : favoriteColor )
Color( type in ( "red", "blue", $color ) )

Person( $color : favoriteColor )
Color( type notin ( "red", "blue", $color ) )

(6)DRL模式约束中的运算符优先级

从最高到最低优先级
从最高到最低优先级

(7)DRL(关键字)中支持的规则条件元素

  • and or

示例模式 and

//Infix `and`:
Color( colorType : type ) and Person( favoriteColor == colorType )

//Infix `and` with grouping:
(Color( colorType : type ) and (Person( favoriteColor == colorType ) or Person( favoriteColor == colorType ))

// Prefix `and`:
(and Color( colorType : type ) Person( favoriteColor == colorType ))

// Default implicit `and`:
Color( colorType : type )
Person( favoriteColor == colorType )
  • exists not (指定必须存在或不存在的事实和约束。仅在第一个匹配项上触发此选项,而不在随后的匹配项上触发,如果将此元素与多个模式一起使用,在模式之间要加上括号())

示例模式 exists

exists Person( firstName == "John")

exists (Person( firstName == "John", age == 42 ))

exists (Person( firstName == "John" ) and
        Person( lastName == "Doe" ))
  • forall (判断是否匹配了第一个模式的所有fact都满足其他模式)

规则示例 forall

rule "All full-time employees have red ID badges"
  when
    forall( $emp : Employee( type == "fulltime" )
                   Employee( this == $emp, badgeColor = "red" ) )
  then
    // True, all full-time employees have red ID badges.
end
  • from (为模式指定数据源)

from与模式绑定的示例规则

rule "Validate zipcode"
  when
    Person( $personAddress : address )
    Address( zipcode == "23920W" ) from $personAddress
  then
    // Zip code is okay.
end
  • entry-point (定义与模式的数据源相对应的入口点或事件流。该元素通常与fromcondition元素一起使用)

规则示例 from entry-point

rule "Authorize withdrawal"
  when
    WithdrawRequest( $ai : accountId, $am : amount ) from entry-point "ATM Stream"
    CheckingAccount( accountId == $ai, balance > $am )
  then
    // Authorize withdrawal.
end

带有EntryPoint对象和插入事实的示例Java应用程序代码

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);
  • collect
  • accumulate
  • eval (执行指定代码)、
p1 : Parameter()
p2 : Parameter()
eval( p1.getList().containsKey( p2.getItem() ) )
p1 : Parameter()
p2 : Parameter()
// call function isValid in the LHS
eval( isValid( p1, p2 ) )

9、DRL中的规则操作(THEN)

then规则的一部分(也称为规则的(RHS))包含满足规则的条件部分时要执行的操作。

(1)DRL中支持的规则操作方法

  • set (使用此设置字段的值)

设置贷款申请批准的值的规则操作示例

$application.setApproved ( false );
$application.setExplanation( "has been bankrupt" );
  • modify (指定要为fact修改的字段,并将更改通知给Drools引擎)

修改贷款申请金额和批准的规则操作示例

modify( LoanApplication ) {
        setAmount( 100 ),
        setApproved ( true )
}
  • update (指定字段和要更新的整个相关事实,并将更改通知给Drools引擎)

更新贷款申请金额和批准的规则操作示例

LoanApplication.setAmount( 100 );
update( LoanApplication );
  • insert (将new事实插入Drools引擎的工作存储器中,并根据事实定义所需的结果字段和值)

插入新贷款申请人对象的规则操作示例

insert( new Applicant() );
  • insertLogical (在new逻辑上将事实插入Drools引擎。Drools引擎负责对事实的插入和撤回进行逻辑决策)

逻辑插入新贷款申请人对象的示例规则操作

insertLogical( new Applicant() );
  • delete (从Drools引擎中删除对象。关键字retract在DRL中也受支持,并执行相同的操作,但delete在DRL代码中通常首选使用该关键字,以与关键字保持一致insert)

删除贷款申请人对象的规则操作示例

delete( Applicant );

(2)具有条件和命名后果的高级规则操作

使用嵌套if和else if构造来评估不同的规则条件

rule "Give free parking and 10% discount to over 60 Golden customer and 5% to Silver ones"
  when
    $customer : Customer( age > 60 )
    if ( type == "Golden" ) do[giveDiscount10]
    else if ( type == "Silver" ) break[giveDiscount5]
    $car : Car( owner == $customer )
  then
    modify($car) { setFreeParking( true ) };
  then[giveDiscount10]
    modify($customer) { setDiscount( 0.1 ) };
  then[giveDiscount5]
    modify($customer) { setDiscount( 0.05 ) };
end

10、DRL中的注释

注释同java,//或/****/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值