几个关键点:
1. 如果没有指定agenda-group 则默认把所有未指定agenda-group的 rules 都执行一遍
2. 如果指定了agenda-group 使用的时候必须指定该name才能被使用,默认是不能使用的
3. agenda-group name可以重复
4. agenda-group 用于区分rule
最简单的使用方法(部分代码参考第一节)
package cn.xiaojf.drools7.base; import org.apache.commons.lang3.StringUtils; import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; public class Base { public KieSession getSession() { KieServices kieServices = KieServices.Factory.get(); KieContainer kieContainer = kieServices.getKieClasspathContainer(); //kmodule.xml 中定义的 ksession name KieSession kieSession = kieContainer.newKieSession("all-rules"); return kieSession; } public KieSession getSession(String agendaGroupName) { KieSession session = this.getSession(); if (StringUtils.isNoneBlank(agendaGroupName)) { session.getAgenda().getAgendaGroup(agendaGroupName).setFocus(); } return session; } }
测试方法
package day20180117; import cn.xiaojf.drools7.base.Base; import cn.xiaojf.drools7.model.Car; import cn.xiaojf.drools7.model.Person; import org.junit.Test; import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; public class Demo extends Base { @Test public void test() { KieSession kieSession = getSession(); Person p1 = new Person(); p1.setAge(20); Car car = new Car(); car.setPerson(p1); kieSession.insert(car); int count = kieSession.fireAllRules(); System.out.println(count); System.out.println(car.getDiscount()); kieSession.dispose(); } @Test public void test2() { KieSession kieSession = getSession("test-group"); Person p1 = new Person(); p1.setAge(20); Car car = new Car(); car.setPerson(p1); kieSession.insert(car); int count = kieSession.fireAllRules(); System.out.println(count); System.out.println(car.getDiscount()); kieSession.dispose(); } }
rule 文件
package cn.xiaojf.rules
import cn.xiaojf.drools7.model.Car;
rule "car-discount>30"
agenda-group "test-group"
when
$car : Car(person.age > 30)
then
$car.setDiscount(80);
end
rule "car-discount<=30"
agenda-group "test-group"
when
$car : Car(person.age <= 30)
then
$car.setDiscount(90);
end
结果如下
1
90