Drools disable a rule at runtime

江枫思渺然 提交于 2019-12-04 03:21:52

There are a few ways of solving this, depending on your requirements and architecture.

  • One way is to define each subset of your rules in different guvnor packages. When building your kbase, you can load only the packages with the rules you want for that kbase in particular.

  • Another way is to always load all the rules, but use an "enabled" expression do dynamically enable/disable rules. Please note that the rules in this case are still evaluated, but they can be prevented from activating. This is a useful technique for cases where you want to enable/disable rules based on the facts you insert into your session. E.g.:

    rule X enabled( ) then ...

    The boolean expression above has access to the variable bindings from the condition of your rule, as well as rule attributes, annotations and obviously you can also access static methods in helper classes if you want to define the conditions to activate the rule external to the DRL file.

  • A third way of doing it is by using agenda filters. In this case you load all your rules, create the session with the facts and when executing the rules you use an agenda filter. An agenda filter is an interface that you can implement yourself or you can use some of the filters that ship with Drools. The filter is called before firing each rule and can then veto or allow the engine to execute the rule. Please note that in this case all rules are evaluated and activated, but only the rules that the filter allows to fire will be fired. E.g., if you want to fire only the rules which have a name that start with "X", you can use the following line of code:

    ksession.fireAllRules( new RuleNameStartsWithAgendaFilter("x") );

    For more info, here is the interface:

    https://github.com/droolsjbpm/droolsjbpm-knowledge/blob/master/knowledge-api/src/main/java/org/drools/runtime/rule/AgendaFilter.java

    Here is the documentation (Scroll down to topic 3.3.3.4.1):

    http://docs.jboss.org/drools/release/5.4.0.Final/drools-expert-docs/html_single/index.html#d0e2792

You may add condition to existence of some fact in working memory. Something like:

rule "RuleA"
when
  not( RuleADisabled() )
  ....
then
  ....
end

and disable the rule in java code:

ksession.insert( new RuleADisabled() );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!