规则引擎 Drools(五):规则分组

Drools 为规则提供了分组机制,使得每次只激活一组规则。

规则属性 agenda-group 声明了当前规则所属的分组

规则属性 lock-on-active 保证同一个分组内的规则,不会被相同的对象再次激活

示例一

DRL 代码:

rule "Group 1"  
    agenda-group "group1"
    lock-on-active

    when
    then
        System.out.println("Group 1");
end

rule "Group 2"  
    agenda-group "group2"
    lock-on-active

    when
    then
        System.out.println("Group 2");
end

rule "Group 3"  
    agenda-group "group3"
    lock-on-active

    when
    then
        System.out.println("Group 3");
end  

Java 代码:

// 执行分组 1
ksession.getAgenda().getAgendaGroup("group1").setFocus();  
ksession.fireAllRules();

// 执行分组 2
ksession.getAgenda().getAgendaGroup("group2").setFocus();  
ksession.fireAllRules();

// 执行分组 3
ksession.getAgenda().getAgendaGroup("group3").setFocus();  
ksession.fireAllRules();  

输出:

Group 1  
Group 2  
Group 3  

示例二

除了在 Java 代码中激活分组外,还可以在 DRL 中使用隐含的全局变量 kcontext 激活分组。

DRL 代码:

rule "Group 1"  
    agenda-group "group1"
    lock-on-active

    when
    then
        System.out.println("Group 1");
        kcontext.getKnowledgeRuntime().getAgenda().getAgendaGroup("group2").setFocus();
end

rule "Group 2"  
    agenda-group "group2"
    lock-on-active

    when
    then
        System.out.println("Group 2");
        kcontext.getKnowledgeRuntime().getAgenda().getAgendaGroup("group3").setFocus();
end

rule "Group 3"  
    agenda-group "group3"
    lock-on-active

    when
    then
        System.out.println("Group 3");
end  

Java 代码:

ksession.getAgenda().getAgendaGroup("group1").setFocus();  
ksession.fireAllRules();  

输出:

Group 1  
Group 2  
Group 3