drools中FactHandle简介&示例
封装基础的获取KieSession的代码Base.java:
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; } }
对应的规则调用程序FaceHandleTest:
/** * 测试 Facehandler * @author xiaojf 2018/1/23 21:35 */ public class FaceHandleTest extends Base { @Test public void test() { KieSession kieSession = super.getSession("faceHandleTest"); Person p = new Person(); p.setAge(30); FactHandle faceHandle = kieSession.insert(p); //触发rules int count = kieSession.fireAllRules(); System.out.println(p.getName()); //在 work memory 中的对象描述信息 System.out.println(faceHandle.toExternalForm()); p.setAge(10); //更新work memory 中的对象信息 kieSession.getAgenda().getAgendaGroup("faceHandleTest").setFocus(); kieSession.update(faceHandle,p); kieSession.fireAllRules(); Person p2 = (Person) kieSession.getObject(faceHandle); System.out.println(p2.getName()); //删除 //kieSession.delete(faceHandle); } }
对应的规则文件内容:
package cn.xiaojf.rules import cn.xiaojf.drools7.model.Person rule "faceHandleTest-less-20" agenda-group "faceHandleTest" when $p : Person(age < 20) then $p.setName("less 20"); end rule "faceHandleTest-more-20" agenda-group "faceHandleTest" when $p : Person(age > 20) then $p.setName("more 20"); end
执行程序对应的结果:
more 20 0:1:429058804:429058804:1:DEFAULT:NON_TRAIT:cn.xiaojf.drools7.model.Person less 20 Process finished with exit code 0
facehandler 相当于是work memory 中对象的句柄,通过facehandler 可以直接定位、修改、删除操作。
关注公众号:程序新视界,一个让你软实力、硬技术同步提升的平台
除非注明,否则均为程序新视界原创文章,转载必须以链接形式标明本文链接