drools规则引擎使用文档
drools規(guī)則引擎使用文檔
文章目錄
- drools規(guī)則引擎使用文檔
- 一、規(guī)則文件結(jié)構(gòu)
- 二、規(guī)則體結(jié)構(gòu)
- 1.Attribute
- 2.Conditions
- 3.Actions
- 三、Query語法
- 1.基本查詢
- 2.位置語法
- 四、類型定義與注解
- 1.類型定義
- 2.預(yù)定義的元數(shù)據(jù)標簽
- 3.java中使用聲明的FactType
一、規(guī)則文件結(jié)構(gòu)
packageimportfunction // Optionalquery // Optionaldeclare // Optionalglobal // Optionalrule "rule name"// Attributeswhen// Conditionsthen// Actions endrule "rule2 name"...-
package:可選,默認值defaultpkg(行尾;可以省略)
若當前kbase指定路徑下所有drl均未指定package,則為defaultpkg;
每個drl文件中僅可出現(xiàn)一次,且必須置于其它代碼之前。
注意:package namespace建議與kbase packages目錄保持一致,否則在最新版本中無法通過kbase獲取package對象。
-
import:可選,自動導入package同名包及java.lang.*下的類;
-
global:可選,一般用于Service服務(wù)類的導入,例如emailService、smsService,甚至是Spring 容器上下文對象applicationContext。
-
依據(jù)上圖import、declare、global、function、query、rule位置是可以互換的。
-
注釋部分 //、/*...*/,可出現(xiàn)在代碼的任何地方,會被編譯器忽略。
示例:
二、規(guī)則體結(jié)構(gòu)
rule "rule_name"// Attribute// Attributewhen// Conditionsthen// Actions end[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-QvYy4GXW-1630918204682)(https://docs.jboss.org/drools/release/7.54.0.Final/drools-docs/html_single/LanguageReference/rule.png)]
1.Attribute
- ruleflow-group和agenda-group概念已統(tǒng)一,ruleflow-group講覆蓋agenda-group屬性。
Since version 6.x the two concepts have been unified, the ruleflow-group name will override the agenda-group.
- Attribute之間可以使用,分割,而非;(,可省略)
- 依據(jù)上圖salience、enabled、date-effective、date-expires、no-loop、agenda-group、activation-group、duration、timer、calendar、auto-focus、lock-on-active、ruleflow-group、dialect、位置是可以互換的。
示例:
package com.example.drools;dialect "mvel"rule "rule1"salience 10enabled truedate-effective "4-Sep-2018"date-expires "4-Sep-2022"no-loop trueagenda-group "agenda-group-1"activation-group "activation-group-1"duration 1000timer (cron:0/10 * * * * ? ) // calendar "* * 0-7,18-23 ? * *"auto-focus falselock-on-active false// 覆蓋agenda-group屬性值 // ruleflow-group "ruleflow-group-1"// 覆蓋包級別方言dialect "java"whenthenSystem.out.println("rule1"); end2.Conditions
條件部分由0個或多個patterns組成,多個pattern之間使用and、or、not組成,默認值and;
pattern括號內(nèi)部由0個或多個constraints約束部分組成,多個constrain可用,分割(,語法上等同于&&,但優(yōu)先級小于&&和||);
- from和entry-point
from和entry-point一起使用,實現(xiàn)eval時載入數(shù)據(jù);
rule "Authorize withdrawal"whenWithdrawRequest( $ai : accountId, $am : amount ) from entry-point "ATM Stream"CheckingAccount( accountId == $ai, balance > $am )then// Authorize withdrawal. end import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.EntryPoint;// Create your KIE base and KIE session as usual: KieSession session = ...// Create a reference to the entry point: EntryPoint atmStream = session.getEntryPoint("ATM Stream");// Start inserting your facts into the entry point: atmStream.insert(aWithdrawRequest);- accumulate
自定義聚合函數(shù)導入
import accumulate AverageAccumulateFunction.AverageData averagerule "Average profit"when$order : Order()accumulate( OrderItem( order == $order, $cost : cost, $price : price );$avgProfit : average( 1 - $cost / $price ) )then// Average profit for `$order` is `$avgProfit`. end3.Actions
- 數(shù)據(jù)操作類
actions包括set、modify、update、insertLogical、delete。
- drools內(nèi)部變量調(diào)用,drools、kcontext
三、Query語法
說明:Query支持可選參數(shù)集合,每一個參數(shù)都有可選的類型。如果沒有指定類型,則默認為Object類型。,支持Query間嵌套調(diào)用;LHS和Rule中的LHS語法一致代表Pattern;Query為了更加緊湊的代碼風格,增加了對positional syntax位置語法的支持。
1.基本查詢
- 無參
- 有參
說明: := 為pattern with unification; 雖然drools不允許重復(fù)聲明"綁定",但是支持跨多個屬性的參數(shù)統(tǒng)一。
示例:
declare PersonFactfirstName : String @position( 1 )lastName : String @position( 0 )age : int @position( 2 )id : int @position( 3 )occupation: String endrule "rule2" when// 約束1 限定firstName和lastName;約束2 限定age范圍;二者使用id統(tǒng)一參數(shù)聲明內(nèi)連接PersonFact("cube", $b:"jack"; $a: age, $id:= id)PersonFact(age<10, $id:= id) thenSystem.out.println($a); endpattern with unification
2.位置語法
positional syntax位置語法用于簡化LHS部分代碼;可混合使用常規(guī)語法和命名語法,兩者使用;分割,但是位置語法必須放于前;
以Location類型為例:
declare Locationthing : Stringlocation : String end- Pattern示例-正確
- Pattern示例-錯誤
四、類型定義與注解
事實類型元數(shù)據(jù)可描述在類級別和字段級別,語法格式為 @key(value),例如@position(0)
1.類型定義
- 無元數(shù)據(jù)描述信息
- 有元數(shù)據(jù)描述信息
2.預(yù)定義的元數(shù)據(jù)標簽
| @role | class | fact,event | fact | 該標記決定在復(fù)雜事件處理期間,給定的事實類型是作為常規(guī)事實對象處理還是作為Drools引擎中的事件對象處理。 |
| @timestamp | class | session clock 或自定義時間戳屬性(可為attribute) | session clock | 支持參數(shù):會話時鐘時間或自定義時間戳屬性 |
| @duration | class | 時間間隔或時間點(可為attribute) | Null (zero) | 該標記決定Drools引擎中事件的持續(xù)時間 |
| @expires | class | [#d][#h][#m][#s][[ms]] | Null (默認時間不在匹配和激活時過期) | 此標記決定事件在Drools引擎的工作內(nèi)存中過期之前的時間。默認情況下,當事件不再匹配和激活任何當前規(guī)則時,該事件將過期。您可以定義事件過期的時間。這個標記定義還覆蓋了根據(jù)時間約束和KIE基中的滑動窗口計算的隱式過期偏移量。只有當Drools引擎以流模式運行時,此標記才可用。 |
| @typesafe | class | true,false | true | 該標記決定給定的事實類型是否使用類型安全進行編譯。 |
| @serialVersionUID | class | integer | Null | 序列化ID,考慮到兼容性建議在相關(guān)類或DRL文件類型聲明過程中顯式指定serialVersionUID(若未指定則根據(jù)類各方面特征自動計算)。 |
| @key | attribute | - | - | 參與計算equals()和hashCode()的屬性;同時Drools引擎會隱式地定義3個構(gòu)造函數(shù),分別為無參構(gòu)造器、全參構(gòu)造器、附帶@key屬性的構(gòu)造器。 |
| @position | attribute | integer | None | 優(yōu)先級原則:子類>父類;顯式指定>未指定;聲明順序 |
| @classReactive | class | - | - | 全局開關(guān)處于開啟狀態(tài)(默認 ALWAYS),代表屬性響應(yīng)性生效;可以通過該標記禁用指定類的屬性響應(yīng)性,實現(xiàn)微調(diào);與ALLOWED對應(yīng),每次觸發(fā)規(guī)則時重新評估事實的所有事實模式。 |
| @propertyReactive | class | - | - | 全局開關(guān)處于可選狀態(tài)(ALLOWED)時,代表屬性響應(yīng)性停用;可以通過該標記啟用指定類的屬性響應(yīng)性,實現(xiàn)微調(diào);與ALWAYS對應(yīng),僅對給定模式內(nèi)受約束或綁定的修改屬性做出反應(yīng)。DISABLED狀態(tài)時,所有屬性更改偵聽器都將被忽略(即不重新評估)。 |
| @watch | factPattern | Property name, * (all), ! (not), !* (no properties) | None | 全局開關(guān)處于開啟狀態(tài)(ALWAYS)或處于可選狀態(tài)(ALLOWED)且類被標記為@propertyReactive時,總之,當前類型處于屬性響應(yīng)性狀態(tài)時,你可以使用通配符或非操作過濾屬性;處于非屬性響應(yīng)性,使用@watch或出現(xiàn)沖突例如@watch( firstName, ! firstName ))時編譯錯誤。 |
| @propertyChangeSupport | class | - | - | 增加該標記,可使drools可以監(jiān)聽javabean的屬性變動。 |
下面以典型的電信領(lǐng)域語音呼叫為例
public class VoiceCall {private String originNumber;private String destinationNumber;private Date callDateTime;private long callDuration; // in milliseconds// Constructors, getters, and setters }- 類級別元數(shù)據(jù)
- @key
- @position
- @watch
- @propertyChangeSupport
3.java中使用聲明的FactType
import java.util.Date;import org.kie.api.definition.type.FactType; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession;...// Get a reference to a KIE base with the declared type: KieBase kbase = ...// Get the declared fact type: FactType personType = kbase.getFactType("org.drools.examples", "Person");// Create instances: Object bob = personType.newInstance();// Set attribute values: personType.set(bob, "name", "Bob" ); personType.set(bob, "dateOfBirth", new Date()); personType.set(bob, "address", new Address("King's Road","London","404"));// Insert the fact into a KIE session: KieSession ksession = ... ksession.insert(bob); ksession.fireAllRules();// Read attributes: String name = (String) personType.get(bob, "name"); Date date = (Date) personType.get(bob, "dateOfBirth");Tips:
a.實際使用過程中,可使用Map簡化操作
org.kie.api.definition.type.FactType#setFromMap
org.kie.api.definition.type.FactType#getAsMap
b.盡管API的行為類似于Java反射,但API并不使用反射,而是依賴于使用生成的字節(jié)碼實現(xiàn)的性能更好的訪問器。
參考:
drools官方文檔
未完待續(xù)……
總結(jié)
以上是生活随笔為你收集整理的drools规则引擎使用文档的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [转]Windows 7 产品密钥是否安
- 下一篇: 鳄鱼mt4复盘助手_免费MT4复盘助手2