rule
规则默认可以重复循环执行,如果只想让规则执行1
次,则将no-loop
属性设置为true
rule "test-rule"
no-loop true
when
then
end
agenda-group
属性用来对规则分组,如下例中两条规则都属于testrule组
,当在代码中调用该组时,会匹配组中所有的规则
rule "test-rule01"
agenda-group "testrule"
when
then
end
rule "test-rule02"
agenda-group "testrule"
when
then
end
调用方式如下,在一个会话中如果多次调用,仍然只会输出一次匹配结果
kieSession.getAgenda().getAgendaGroup("testrule").setFocus();
ruleflow-group
与agenda-group
分组效果一样
activation-group
属性组中的规则只要有一个被执行,其它的则不再执行,具有排他性,默认值为false
下面示例中只要任意一个匹配成功,其它的则不会再执行
rule "test-rule01"
activation-group "testrule"
when
then
end
rule "test-rule02"
activation-group "testrule"
when
then
end
rule "test-rule03"
activation-group "testrule"
when
then
end
lock-on-active
属性用于指定某条规则,值设置为true
时免于被其它规则输出的fact对象干扰。比如其它规则执行update、modify等操作后,FACT对象中的属性值被更新,而该值正好触发其它规则的判断条件,这样就会出现规则间的干扰
如下例中,规则1
执行完后update($b)
,将income
设置为10001
,刚好满足规则2
触发条件,如果不设置lock-on-active true
,那么规则2
也会触发,这里需要根据实际需求判断是否添加该属性。
rule "lock-on-active-1"
when
$b : Borrower( income < 10000)
then
System.out.println("lock-on-active-1触发,income=" + $b.getIncome());
$b.setIncome(new BigDecimal(10001));
update($b)
end
rule "lock-on-active-2"
lock-on-active true
when
$b : Borrower(income > 10000)
then
System.out.println("lock-on-active-2触发,income=" + $b.getIncome());
end
通过指定salience
属性值来控制规则执行顺序,其默认值为0
,数值越大优先级越高,也可以为负数
下面示例执行顺序为test-rule1
、test-rule2
、test-rule3
rule "test-rule1"
salience 5
when
then
end
rule "test-rule2"
salience 0
when
then
end
rule "test-rule3"
salience -2
when
then
end
date-effective
属性表示生效时间,可以与系统时间比对,根据条件在指定时间执行,默认格式为dd-MMM-yyyy
,下面示例表示只要到了2020年7月15日才会执行该规则
rule "test-rule1"
date-effective "15-Jul-2020"
when
then
end
自定义时间为yyyy-MM-dd HH:mm
格式,在创建KieSession
会话前加一行设置代码即可
System.setProperty("drools.dateformat","yyyy-MM-dd HH:mm");
KieSession kieSession = kieContainer.newKieSession("date-effective-rules");
...
表示只要到了2020年7月15日上午9点30分才会执行该规则
rule "test-rule1"
date-effective "2020-7-15 9:30"
when
then
end
date-expires
属性表示失效时间,用法与date-effective
一样
定时器是通过timer()
函数进行设置,有两种格式可以使用
1)格式一:timer ( int:
,第一个参数表示初始执行时间,第二个参数表示执行间隔时间,比如timer ( int: 1m 10m )
表示运行后1分钟开始执行第一次,往后每个10分钟执行一次
2)格式二:timer ( cron:
cron表达式详细用法请参考Cron表达式常见用法
下面示例表示为每天凌晨 2 点执行
rule "test-rule1"
timer (cron:0 0 2 * * * )
when
then
end
enabled
属性设置规则是否可以,默认为true
可用,设置为false
则不可用
rule "test-rule1"
enabled true
when
then
end
rule "test-rule2"
enabled false
when
then
end
dialect
默认为java
,也可以指定为mvel
rule "test-rule1"
dialect "java"
when
then
end
rule "test-rule2"
dialect "mvel"
when
then
end