• 沒有找到結果。

4 规则

4.6 RHS 语法

4.6.1 使用说明

RHS 是满足 LHS 条件之后进行后续处理部分的统称,该部分包含要执行的操作的列表信 息。RHS 主要用于处理结果,因此不建议在此部分再进行业务判断。如果必须要业务判断需 要考虑规则设计的合理性,是否能将判断部分放置于 LHS,那里才是判断条件应该在的地方。

同时,应当保持 RHS 的精简和可读性。

如果在使用的过程中发现需要在 RHS 中使用 AND 或 OR 来进行操作,那么应该考虑将 一根规则拆分成多个规则。

RHS 的主要功能是对 working memory 中的数据进行 insert、update、delete 或 modify 操

insert(newSomething()):创建一个新对象放置到 working memory 中。

insertLogical(newSomething()):功能类似于 insert,但当创建的对象不再被引用时,将会 被销毁。

delete(handle):从 working memory 中删除对象。

其实这些宏函数是 KnowledgeHelper 接口中方法对应的快捷操作,通过它们可以在规则 文 件 中 访 问 Working Memory 中 的 数 据 。 预 定 义 变 量 drools 的 真 实 类 型 就 是 KnowledgeHelper,因此可以通过 drools 来调用相关的方法。具体每个方法的使用说明可以 参考类中方法的说明。

通过预定义的变量 kcontext 可以访问完整的 Knowledge Runtime API,而 kcontext 对应 的接口为 KieContext。查看 KieContext 类会发现提供了一个 getKieRuntime()方法,该方法 返回 KieRuntime 接口类,该接口中提供了更多的操作方法,对 RHS 编码逻辑有很大作用。

4.6.2 insert 函数

insert 的作用与在 Java 类当中调用 KieSession 的 insert 方法效果一样,都是将 Fact 对象 插入到当前的 Working Memory 当中,基本用法格式如下:

insert(newSomething());

调用 insert 之后,规则会进行重新匹配,如果没有设置 no-loop 为 true 或 lock-on-active 为 true 的规则,如果条件满足则会重新执行。update、modify、delete 都具有同样的特性,

因此在使用时需特别谨慎,防止出现死循环。

System.out.println("insert-check:insert Product success and it's type is " +

$p.getType());

end

rule "insert-action"

salience 2 when

then

System.out.println("insert-action : To insert the Product");

Product p = new Product();

p.setType(Product.GOLD);

insert(p);

end

测试代码:

@Test

public void commonTest(){

KieServices kieServices = KieServices.get();

KieContainer kieContainer =

kieServices.getKieClasspathContainer();

KieSession kieSession =

kieContainer.newKieSession("ksession-rule");

int count = kieSession.fireAllRules();

kieSession.dispose();

System.out.println("Fire " + count + "

rules!");

}

打印日志:

insert-action : To insert the Product

insert-check:insert Product success and it's type is GOLD Fire 2 rules!

根据优先级首先执行 insert 操作的规则,然后执行结果检测。

4.6.3 update 函数

update 函数可对 Working Memory 中的 FACT 对象进行更新操作,与 StatefulSession 中 的 update 的作用基本相同。查看 KnowledgeHelper 接口中的 update 方法可以发现,update 函数有多种参数组合的使用方法。在实际使用中更多的会传入 FACT 对象来进行更新操作。

具体的使用方法前面章节已经有具体例子,不再重复示例。

4.6.4 delete 函数

将 Working Memory 中的 FACT 对象删除,与 kession 中的retract/delete 方法效果一 样。同时 delete 函数和 retract 效果也相同,但后者已经被废弃。

4.6.5 modify 函数

modify 是基于结构化的更新操作,它将更新操作与设置属性相结合,用来更改 FACT 对 象的属性。语法格式如下:

modify ( <fact-expression> ) { <expression> [ , <expression> ]*

}

其中<fact-expression>必须是 FACT 对象的引用,expression 中的属性必须提供 setter 方 法。在调用 setter 方法时,不必再写 FACT 对象的引用,编译器会自动添加。

rule "modify stilton"

when

$stilton : Cheese(type == "stilton") then

modify( $stilton ){

setPrice( 20 ), setAge( "overripe" ) }

end

相關文件