Drools的基本使用和原理

部分转载自

https://blog.csdn.net/chinrui/article/details/74906748

基本使用

         // load up the knowledge base
         KnowledgeBase kbase = readKnowledgeBase();
         StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
         
         ItemCity item1 = new ItemCity();
         item1.setPurchaseCity(City.PUNE);
         item1.setTypeofItem(Type.MEDICINES);
         item1.setSellPrice(new BigDecimal(10));
         ksession.insert(item1);
         
         ItemCity item2 = new ItemCity();
         item2.setPurchaseCity(City.PUNE);
         item2.setTypeofItem(Type.GROCERIES);
         item2.setSellPrice(new BigDecimal(10));
         ksession.insert(item2);
         
         ItemCity item3 = new ItemCity();
         item3.setPurchaseCity(City.NAGPUR);
         item3.setTypeofItem(Type.MEDICINES);
         item3.setSellPrice(new BigDecimal(10));
         ksession.insert(item3);
         
         ItemCity item4 = new ItemCity();
         item4.setPurchaseCity(City.NAGPUR);
         item4.setTypeofItem(Type.GROCERIES);
         item4.setSellPrice(new BigDecimal(10));         
         ksession.insert(item4);
         
         ksession.fireAllRules();
         
         System.out.println(item1.getPurchaseCity().toString() + " " 
            + item1.getLocalTax().intValue());
         
         System.out.println(item2.getPurchaseCity().toString() + " "
            + item2.getLocalTax().intValue());
         
         System.out.println(item3.getPurchaseCity().toString() + " "
            + item3.getLocalTax().intValue());
         
         System.out.println(item4.getPurchaseCity().toString() + " "

RETE算法

主要思想
其核心思想是用分离的匹配项构造匹配网络,同时缓存中间结果。以空间换时间。规则编译(rule compilation)和运行时执行(runtime execution)。

RETE网络的示意图如下
Drools的基本使用和原理_第1张图片

  • Root Node 所有对象进入网络的入口。一个网络中只有一个跟节点。
    https://www.jianshu.com/p/3e9afe9e0617

原理

  • 模式(Module)
  • 规则(RULE)
  • 事实(FACT)
    Drools的基本使用和原理_第2张图片
    事实会和规则进行匹配,以推断相应的规则结果,这个过程称为模式匹配。

Drools 规则引擎将业务规则转换成执行树
Drools的基本使用和原理_第3张图片

规则引擎默认不会在规则评估时立即执行业务规则,除非我们强制指定。当我们到达一个事实(Fact)与规则相匹配的节点时,规则评估会将规则操作与触发数据添加到一个叫作议程(Agenda)的组件中,如果同一个事实(Fact)与多个规则相匹配,就认为这些规则是冲突的,议程(Agenda)使用冲突解决策略(Conflict Resolution strategy)管理这些冲突规则的执行顺序。整个生命周期中,规则评估与规则执行之间有着明确的分割。规则操作的执行可能会导致事实(Fact)的更新,从而与其它规则相匹配,导致它们的触发,称之为前向链接。

Drools的基本使用和原理_第4张图片

你可能感兴趣的:(java)