首页 > 解决方案 > 在drools中停用规则流组

问题描述

我有一个 drl 文件,其中包含 2 个规则流组内的规则: "first-ruleflow-group" 和 "second-ruleflow-group" 。这些组的激活取决于“规则 A”和“规则 B”。有什么方法可以在规则 A 条件匹配时停用规则 B 以使焦点仅设置为“first-ruleflow-group”?

rule "rule A"
    when
        eval(true);
   then
        drools.setFocus("first-ruleflow-group");
end

rule "rule B"
    when
        eval(true);
   then
        drools.setFocus("second-ruleflow-group");
end

标签: drools

解决方案


更改您的规则依赖于排他性条件。

简单的例子。假设我们有一个处理日历事件的应用程序。我们有公共假期的规则流程。我们有宗教节日的规则流程。有一些宗教节日也是公众假期;对于这些,我们只想解除公共假期规则。

rule "Public Holidays"
when
  Holiday( isPublic == true )
then
  drools.setFocus("publicholiday-flow");
end

rule "Religious Holidays"
when
  Holiday( isReligious == true,
           isPublic == false )
then
  drools.setFocus("religiousholiday-flow");
end

因此,基本上,修改您的“规则 B”以包含否定规则 A 条件的条件,这样如果规则 A 匹配,则规则 B 必然不匹配。


第二种解决方案是在您的第一个规则流(由 A 触发)中设置一个规则,以使规则 B 不会触发。除了阻止规则 B 触发的条件是动态的之外,它与之前的解决方案基本相似。

举个例子,想象一个应用程序可以确定某人的停车费。停车费是按天计算的——周一到周五有一个费率,周六有一个费率,周日是免费的。此外,还有其他折扣适用——例如老年人,或者如果总停车时间少于 5 分钟。星期几费率使用第一个规则流 (A) 确定,折扣使用第二个规则流 (B) 确定。如果是星期天,就没有理由取消第二套规则。

您可以编写折扣规则流触发器以明确不针对星期日触发,或者您可以让星期日汇率规则撤回或插入数据,以使折扣规则不再有效运行。

rule "Day Rates"
when
then
  drools.setFocus("dayrates-flow");
end

rule "Discounts"
when
  exists(Rate( hourly > 0 ))
then
  drools.setFocus("discounts-flow");
end

// The Sunday rule, part of the dayrates-flow, sets hourly = 0, which makes
// the "Discounts" rule no longer valid to fire.
rule "Sunday Rate"
ruleflow-group "dayrates-flow"
when
  not(Rate())
  Request( day == DayOfWeek.SUNDAY ) // when parking on Sunday...
then
  Rate rate = new Rate();
  rate.setHourlyRate(0.0);
  insert(rate);
end

另一种选择是从第一规则流内触发第二规则流,但仅在需要时。

重用前面的停车示例:

rule "Day Rates"
when
then
  drools.setFocus("dayrates-flow");
end


// Here are some day rate rules. Most are omitted for brevity. We include three (3)
// to show regular rates, the special case of Sunday, and how we trigger the discount
// rate rules

rule "Saturday Rate"
ruleflow-group "dayrates-flow"
when
  not(Rate())
  Request( day == DayOfWeek.SATURDAY )
then
  Rate rate = new Rate();
  rate.setHourly(1.0); // Saturday rate: $1/hr
  insert(rate);
end

rule "Sunday Rate"
ruleflow-group "dayrates-flow"
when
  not(Rate())
  Request( day == DayOfWeek.SUNDAY )
then
  Rate rate = new Rate();
  rate.setHourlyRate(0.0); // Sunday rate: free
  insert(rate);
end

// This rule only triggers the next rule flow when the rate is positive (eg not Sunday)
rule "Transition to Discounts"
ruleflow-group "dayrates-flow"
when
  exists(Rate( hourly > 0 ))
then
  drools.setFocus("discount-flow");
end

推荐阅读