【java规则引擎】《Drools7.0.0.Final规则引擎教程》第4章 4.2 auto-focus

转载至:https://blog.csdn.net/wo541075754/article/details/75349556

auto-focus

在agenda-group章节,我们知道想要让AgendaGroup下的规则被执行,需要在代码中显式的设置group获得焦点。而此属性可配合agenda-group使用,代替代码中的显式调用。默认值为false,即不会自动获取焦点。设置为true,则可自动获取焦点。

对于规则的执行的控制,还可以使用org.kie.api.runtime.rule. AgendaFilter来实现。用户可以实现该接口的accept方法,通过规则当中的属性值来控制是否执行规则。 
方法体如下:

boolean accept(Match match);
View Code

在该方法当中提供了一个Match参数,通过该参数可以获得当前正在执行的规则对象和属性。该方法要返回一个布尔值,返回true就执行规则,否则不执行。

auto-focus使用示例代码

规则代码:

package com.rules

 rule "test agenda-group"

    agenda-group "abc"
    auto-focus true

    when
    then
        System.out.println("规则test agenda-group 被触发");
    end
View Code

执行规则代码:

KieServices kieServices = KieServices.Factory.get();
KieContainer kieContainer = kieServices.getKieClasspathContainer();
KieSession kSession = kieContainer.newKieSession("ksession-rule");
kSession.fireAllRules();
kSession.dispose();
View Code

执行结果:

规则test agenda-group 被触发
View Code

这里,我们没有在代码中显式的让test agenda-group获取焦点,但规则同样被执行了,说明属性配置已生效。

AgendaFilter代码实例

规则文件代码:

package com.rules

 rule "test-agenda-group"

    when
    then
        System.out.println("规则test-agenda-group 被触发");
    end

rule other

    when
    then
        System.out.println("规则other被触发");
    end
View Code

实现的MyAgendaFilter代码:

package com.secbro.drools.filter;

import org.kie.api.runtime.rule.AgendaFilter;
import org.kie.api.runtime.rule.Match;

/**
 * Created by zhuzs on 2017/7/19.
 */
public class MyAgendaFilter implements AgendaFilter{

    private String ruleName;

    public MyAgendaFilter(String ruleName) {
        this.ruleName = ruleName;
    }

    @Override
    public boolean accept(Match match) {
        return match.getRule().getName().equals(ruleName) ? true : false;
}
// 省略getter/setter方法
}
View Code

测试方法:

KieServices kieServices = KieServices.Factory.get();
KieContainer kieContainer = kieServices.getKieClasspathContainer();
KieSession kSession = kieContainer.newKieSession("ksession-rule");

AgendaFilter filter = new MyAgendaFilter("test-agenda-group");
kSession.fireAllRules(filter);
kSession.dispose();
View Code

执行结果:

规则test-agenda-group 被触发
View Code

在执行规则的Filter中传入的规则名称为test-agenda-group,此规则被执行。而对照组的规则other,却未被执行。

原文地址:https://www.cnblogs.com/shangxiaofei/p/9439197.html