《Drools7.0.0.Final规则引擎教程》FactHandler使用案例详解编程语言

背景

在使用具体的业务使用中,我们经常会通代码对Fact对象进行操作,Drools为我们提供了FactHandler来获取对象的句柄,通过此返回值可以对WorkingMemory中Fact对象进行操作。

实例代码

规则文件内容:

package com.rules 
import com.secbro.drools.model.Person 
 rule "fact-handler-test" 
    agenda-group "fact-handler-group" 
    when 
        $p : Person(age > 80) 
    then 
        System.out.println($p.getAge()); 
     end

调用测试方法:

@Test 
    public void testFactHandler(){ 
        KieSession kieSession = this.getKieSession("fact-handler-group"); 
 
        Person p = new Person(); 
        p.setAge(81); 
 
        FactHandle handle = kieSession.insert(p); 
 
        System.out.println(handle.toExternalForm()); 
 
        int count = kieSession.fireAllRules(); 
        System.out.println("Fires " + count + " rules!"); 
 
        p.setAge(90); 
        kieSession.getAgenda().getAgendaGroup("fact-handler-group").setFocus(); 
        kieSession.update(handle,p); 
 
        count =  kieSession.fireAllRules(); 
 
        System.out.println("Fires " + count + " rules!"); 
        kieSession.dispose(); 
    }

上面的实例中,首先通过FactHandler获取WM中Person对象的具体信息。后面又通过FactHandler对WM中Fact对象进行修改,并重新调用规则。

由于代码中使用的是agenda group,因此重新设置获取焦点。如果未使用此中形式则可不用写此行代码。其他相关FactHandler的使用方法可在此示例上进行扩展延伸。

相关代码以上传至github:https://github.com/secbr/drools

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/15184.html

(0)
上一篇 2021年7月19日 17:34
下一篇 2021年7月19日 17:34

相关推荐

发表回复

登录后才能评论