Drools入门之指定规则名调用
RuleNameEqualsAgendaFilter
rule "name1"
when
then
System.out.println("调用规则:"+drools.getRule().getName());
end
rule "name2"
when
then
System.out.println("调用规则:"+drools.getRule().getName());
end
@Test
public void testRuleNameInvoking() {
KieServices kieService = KieServices.Factory.get();
KieContainer kieContainer = kieService.getKieClasspathContainer();
KieSession kieSession = kieContainer.newKieSession("testInvoking");
// kieSession.fireAllRules();
kieSession.fireAllRules(new RuleNameEqualsAgendaFilter("name1"));
kieSession.dispose();
}
}
执行日志
调用规则:name1
RuleNameEqualsAgendaFilter:比较规则名称是否如传入的一致
RuleNameEndsWithAgendaFilter
根据指定的规则名称后缀进行匹配
RuleNameStartsWithAgendaFilter
根据指定的规则名称前缀过滤
RuleNameMatchesAgendaFilter
根据指定的规则名称正则匹配过滤
自定义执行过滤器
AgendaFilter是一个接口,需要写一个类并实现AgendaFilter接口。创建CustomAgendaFilter.java文件,目录为comTwo/ruleName,其内容为:
public class CustomAgendaFilter implements AgendaFilter {
private final Set<String> ruleNamesThatAreAllowedToFire; //传入的rule
public CustomAgendaFilter(Set<String> ruleNamesThatAreAllowedToFire) {
this.ruleNamesThatAreAllowedToFire = ruleNamesThatAreAllowedToFire;
}
@Override
public boolean accept(Match match) {
return ruleNamesThatAreAllowedToFire.contains(match.getRule().getName());
}
}
@Test
public void testCustomRuleNameInvoking() {
KieServices kieService = KieServices.Factory.get();
KieContainer kieContainer = kieService.getKieClasspathContainer();
KieSession kieSession = kieContainer.newKieSession("testInvoking");
Set<String> set = new HashSet<>();
set.add("name1");
set.add("test1");
kieSession.fireAllRules(new CustomAgendaFilter(set));
kieSession.dispose();
}
}
执行日志
调用规则:name1
调用规则:test1
对指定规则名调用方法做以下总结。
- “int fireAllRules()”执行所有满足条件的规则。
- “int fireAllRules(int max)”执行规则的最大数量,简单地说,即执行多少条规则。
- “int fireAllRules(AgendaFilter agendaFilter)”指定规则名的方式。
- “int fireAllRules(AgendaFilter agendaFilter,int max);”指定规则名,并设置执行规则的最大数量,在精确匹配中是不适用的。
Drools入门之指定规则名调用
https://www.zhaojun.inkhttps://www.zhaojun.ink/archives/drools-invoking-name