Drools規則引擎入門指南(二)

本篇博客主要講解Drools常用的屬性以及函數

屬性

首先我們在resources\rules文件夾下創建一個Property.drl,還有一個DroolsApplicationPropertyTests

1. salience優先級

salience 屬性的值默認爲0,它的值越大執行的優先級就越高,看如下代碼在執行的時候就會先執行salience2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 rule "salience2"
salience 2
    when
        eval(true)
    then
        System.err.println("salience2");
end

rule "salience1"
salience 1
    when
        eval(true)
    then
        System.err.println("salience1");
end
1
2
3
4
@Test
   public void testSalience() {
       kieSession.fireAllRules();
   }

2. date-effective日期比較(小於等於)

當系統時間小於等於date-effective的值是纔會執行。

1
2
3
4
5
6
7
8
9
10
11
12
13
 rule "dateEffective"
date-effective "2018-11-24"
    when
    then
        System.err.println("2018-11-24被執行");
end

rule "dateEffectiveTomorrow"
date-effective "2018-11-25"
    when
    then
        System.err.println("2018-11-25被執行");
end
1
2
3
4
5
6
7
8
9
@Test
public void testDateEffective() {
    kieSession.fireAllRules(new RuleNameEndsWithAgendaFilter("dateEffective"));
}

@Test
public void testDateEffectiveTomorrow() {
    kieSession.fireAllRules(new RuleNameEndsWithAgendaFilter("dateEffectiveTomorrow"));
}

由於今天是11月24,所以上方的dateEffectiveTomorrow將不會執行。

還有需要注意的是Drools默認的時間格式是dd-MMM-yyyy的,也就是說你必須使用24-十一月-2018它才能識別,我爲什麼能使用yyyy-MM-dd呢,請參考上篇文章中進行自動配置時的getKieServices()方法

3. date-expires日期比較(大於)

剛好於date–effective相反

4. enabled

當一個規則的enabled屬性變爲false時這條規則將不再可用

1
2
3
4
5
6
rule "enabled"
enabled false
    when
    then
        System.err.println("被禁用的規則");
end
1
2
3
4
@Test
    public void testEnabled() {
        kieSession.fireAllRules(new RuleNameEndsWithAgendaFilter("enabled"));
    }

函數

接着我們在resources\rules文件夾下創建一個Function.drl,還有一個DroolsApplicationFunctionTests

Drools中常用函數分別爲insert、update和retract,分別是插入更新和刪除,我們來看一下下方的幾個規則的執行過程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
rule "test1"
    when

    then
      insert(new User("趙六",12));
      System.err.println("創造趙六");
end

rule "test2"
    when
       $u:User(name=="趙六")
    then
        $u.setName("王五");
        update($u);
        System.err.println("趙六");
end

rule "test3"
    when
         $u:User(name=="王五")
    then
        System.err.println("王五");
        retract($u);
end

rule "test4"
    when
         $u:User(name=="王五")
    then
        System.err.println("王五刪除刪除之後"+$u.getName());
end

可用看的,test1規則沒有判斷條件,所以直接被執行,執行過程中它生成了一個對象插入到工作內存中,此對象的規則又恰好與test2規則匹配,所以緊接着test2執行,test2執行時更新了user對象,更新後的對象又匹配了test3,所以test3繼續執行。執行完畢後user對象被刪除,test4就執行不了了。

另外還有幾個方法也是常用的:

  1. getWorkingMemory,獲取當前的WorkingMemory對象
  2. halt,執行完當前規則後不再執行其他規則
  3. getRule,獲取當前規則對象

本文所有源碼:https://github.com/shiyujun/drools

本文出自http://zhixiang.org.cn/,轉載請保留

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章