代码地址:https://github.com/ImTravis/drools
规则组
activation-group
该属性将若干个规则划分成一个组,统一命名。在执行的时候,具有相同activation-group 属性的规则中只要有一个被执行,其它的规则都不再执行。同时可以用类似salience之类属性来实现组内规则的执行优先级。
业务逻辑:
规则1:对成绩小于70分的同学要短信通知家长
规则2:对应成绩小于60分的同学要通知家长见面 优先级大于规则1(实际:规则2 包含规则1)
首先不用:activation-group
student-rule.drl 中添加规则
rule "gradeLowSeventy" salience 100 when $stu : StudentFact(grade < 70) then final Logger LOGGER = LoggerFactory.getLogger("成绩低于70分→→→→") ; LOGGER.info("***你家孩子:"+$stu.getName()+"成绩低于70分,快不及格了,得多督促\n"); end
rule "gradeLowSixty" salience 100 when $stu : StudentFact(grade < 60) then final Logger LOGGER = LoggerFactory.getLogger("成绩低于60分→→→→") ; LOGGER.info("***你家孩子:"+$stu.getName()+"成绩不及格,明天过来开家长会\n"); end |
StudentAgeRuleTest 新建测试
/** * 技术点:activation-group * 对低于70、60分的同学进行处理 */ @Test public void gradeLow(){ StudentFact studentFact = new StudentFact(); studentFact.setAge(19); studentFact.setGrade(59); studentFact.setName("莉莉"); kieSession.insert(studentFact); int sum = kieSession.fireAllRules(new RuleNameStartsWithAgendaFilter("gradeLow")); System.out.print("sum:"+sum); } |
运行
其实,当成绩低于60分的时候,直接通知家长开会,无需再通知家长成绩低于70分(规则1 冗余)
添加:activation-group
修改之后如下
如果同组中的优先级相等,则按照由上至下的顺序执行(组内第一个)
agenda-group
上面我们对Fact数据(即参数对象)进行规则匹配的时候,筛选规则是通过以下三种方式:
#匹配所有加载的规则
kieSession.fireAllRules()
#匹配前缀为gradeLow的规则
kieSession.fireAllRules(new RuleNameStartsWithAgendaFilter("gradeLow"));
#匹配后缀为checkAge的规则
kieSession.fireAllRules(new RuleNameEndsWithAgendaFilter("checkAge"));
agenda-group组内的规则处于未激活状态,kieSession中没有该组的规则,所以以上三种方式都不能对它进行匹配;fireAllRules只能对kieSession中有的规则进行Filter筛选
加载的方式:
例如组 agenda-group "gradeLow"
kieSession.getAgenda().getAgendaGroup("gradeLow").setFocus();
上面的例子修改如下:
添加测试类
/** * 技术点:agenda-group * 对低于70、60分的同学进行处理 */ @Test public void gradeLow_aAgendaGroup(){ StudentFact studentFact = new StudentFact(); studentFact.setAge(19); studentFact.setGrade(59); studentFact.setName("莉莉"); kieSession.getAgenda().getAgendaGroup("gradeLow").setFocus(); kieSession.insert(studentFact); int sum = kieSession.fireAllRules(); System.out.print("sum:"+sum); } |
运行结果:
注释掉:kieSession.getAgenda().getAgendaGroup("gradeLow").setFocus();
结果
总结、agenda-group组下的规则必须通过KieSession去激活加载