1. Background

In the process of writing our drools rules file, many rules may be written. drools When the engine is pattern matching, it may activate a lot of rules at once, but I only want to execute a specified rule, so what should I do at this time?

2. Scheme

2.1 Implemented by AgendaFilter

We know that when the drools pattern is matched, all the rules will be matched, and the successfully matched rules will be put into Agenda (the agenda), and fireAllRules(AgendaFilter) method, you can pass a AgendaFilter to filter the active rules in Agenda .

2.2 Implemented through entry-point

Use entry-point to define the entry point or event flow corresponding to the data source of the schema. This can't be fully realized, just to provide an idea.

for example:

 Api(api == "/users/info" ) from entry-point "first-entry-point"
 Api api = new Api("/users/info", 100);
EntryPoint entryPoint = kieSession.getEntryPoint("second-entry-point");
entryPoint.insert(api);
kieSession.fireAllRules();

In the above example, although the object Api exists in the working memory, because the rule entry-point is inconsistent with the entry-point in the java code, the rule is not matched successfully.

3. Realize

Here we use AgendaFilter to implement a specific call to a specific rule.

3.1 Requirements

We have a Api(api,invokedCnt) object

Rule 1: There is a Api object in the working memory, and the attribute api=="/users/info" .
Rule 2: There is a Api object in the working memory, and the attribute invokedCnt > 10 .

We insert a Api("/users/info",100) into the working memory, and both rule 1 and rule 2 will match, but I only want to execute rule 2.

3.2 drl file writing

 package rules

import com.huan.drools.Api

rule "rule_agenda_filter_01"
    when
        $api: Api(api == "/users/info" )
    then
        System.out.println("当前执行的规则是: " + drools.getRule().getName());
end

rule "rule_agenda_filter_02"
    when
        $api: Api(invokedCnt > 10)
    then
        System.out.println("当前执行的规则是: " + drools.getRule().getName());
end

3.3 Part of the java code

 Api api = new Api("/users/info", 100);
kieSession.insert(api);

// 所有模式匹配成功后的规则回进入到agenda中,然后通过AgendaFilter过滤出需要执行的规则
kieSession.fireAllRules(new AgendaFilter() {
    @Override
    public boolean accept(Match match) {
        String ruleName = match.getRule().getName();
        return Objects.equals(ruleName, "rule_agenda_filter_02");
    }
});

It can be seen that the rules are filtered by AgendaFilter , and only the rule_agenda_filter_02 rule is executed.

注意: Although this is a filter, it does not mean that only the rule_agenda_filter_02 rule is activated, but all rules that meet the conditions are activated.

3.4 Running Results

 当前执行的规则是: rule_agenda_filter_02

It can be seen that the desired result is achieved.

4. Complete code

https://gitee.com/huan1993/spring-cloud-parent/tree/master/drools/drools-invoked-specify-rule


huan1993
218 声望34 粉丝

java工程师