日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

drools规则引擎使用文档

發布時間:2023/12/10 编程问答 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 drools规则引擎使用文档 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

drools規則引擎使用文檔

文章目錄

  • drools規則引擎使用文檔
    • 一、規則文件結構
    • 二、規則體結構
      • 1.Attribute
      • 2.Conditions
      • 3.Actions
    • 三、Query語法
      • 1.基本查詢
      • 2.位置語法
    • 四、類型定義與注解
      • 1.類型定義
      • 2.預定義的元數據標簽
      • 3.java中使用聲明的FactType

一、規則文件結構

packageimportfunction // Optionalquery // Optionaldeclare // Optionalglobal // Optionalrule "rule name"// Attributeswhen// Conditionsthen// Actions endrule "rule2 name"...

  • package:可選,默認值defaultpkg(行尾;可以省略)

    若當前kbase指定路徑下所有drl均未指定package,則為defaultpkg;

    每個drl文件中僅可出現一次,且必須置于其它代碼之前。

    注意:package namespace建議與kbase packages目錄保持一致,否則在最新版本中無法通過kbase獲取package對象。

  • import:可選,自動導入package同名包及java.lang.*下的類;

  • global:可選,一般用于Service服務類的導入,例如emailService、smsService,甚至是Spring 容器上下文對象applicationContext。

  • 依據上圖import、declare、global、function、query、rule位置是可以互換的。

  • 注釋部分 //、/*...*/,可出現在代碼的任何地方,會被編譯器忽略。

    示例:

二、規則體結構

rule "rule_name"// Attribute// Attributewhen// Conditionsthen// Actions end

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(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概念已統一,ruleflow-group講覆蓋agenda-group屬性。

Since version 6.x the two concepts have been unified, the ruleflow-group name will override the agenda-group.

  • Attribute之間可以使用,分割,而非;(,可省略)
  • 依據上圖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"); end

2.Conditions

條件部分由0個或多個patterns組成,多個pattern之間使用and、or、not組成,默認值and;

pattern括號內部由0個或多個constraints約束部分組成,多個constrain可用,分割(,語法上等同于&&,但優先級小于&&和||);

  • from和entry-point

from和entry-point一起使用,實現eval時載入數據;

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

自定義聚合函數導入

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`. end

3.Actions

  • 數據操作類

actions包括set、modify、update、insertLogical、delete。

  • drools內部變量調用,drools、kcontext
rule "rule2"whenthenSystem.out.println(drools.getRule().getName());System.out.println(kcontext.getKieRuntime().getEnvironment()); end

三、Query語法

![query](https://img-blog.csdnimg.cn/img_convert/7cdf82c54ac3ffbbcc3f528b13a8341c.png)

說明:Query支持可選參數集合,每一個參數都有可選的類型。如果沒有指定類型,則默認為Object類型。,支持Query間嵌套調用;LHS和Rule中的LHS語法一致代表Pattern;Query為了更加緊湊的代碼風格,增加了對positional syntax位置語法的支持。

1.基本查詢

  • 無參
query "people under the age of 21"$person : Person( age < 21 ) end
  • 有參
query contains(String $s, String $c)$s := String( this.contains( $c ) ) end

說明: := 為pattern with unification; 雖然drools不允許重復聲明"綁定",但是支持跨多個屬性的參數統一。

示例:

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統一參數聲明內連接PersonFact("cube", $b:"jack"; $a: age, $id:= id)PersonFact(age<10, $id:= id) thenSystem.out.println($a); end

pattern with unification

2.位置語法

positional syntax位置語法用于簡化LHS部分代碼;可混合使用常規語法和命名語法,兩者使用;分割,但是位置語法必須放于前;

以Location類型為例:

declare Locationthing : Stringlocation : String end
  • Pattern示例-正確
Location(thing == x, location == y) Location(x; location == y) Location(x, y;) // x-代表position為0的字段即thing y-代表position為1的字段即location Location(x; $p:location == y) // $p-代表patternBinding參數 Location(x; $p:location) // 同上 Location(x, $p;) // 同上
  • Pattern示例-錯誤
Location(thing == x, y;) Location(thing == x; y;)

四、類型定義與注解

事實類型元數據可描述在類級別和字段級別,語法格式為 @key(value),例如@position(0)

1.類型定義

  • 無元數據描述信息
import java.util.Datedeclare Personname : StringdateOfBirth : Dateaddress : Address end
  • 有元數據描述信息
import java.util.Datedeclare Person@author( Bob )@dateOfCreation( 01-Feb-2009 )name : String @key @maxLength( 30 )dateOfBirth : Dateaddress : Address end

2.預定義的元數據標簽

元數據作用域可選值默認值描述
@roleclassfact,eventfact該標記決定在復雜事件處理期間,給定的事實類型是作為常規事實對象處理還是作為Drools引擎中的事件對象處理。
@timestampclasssession clock 或自定義時間戳屬性(可為attribute)session clock支持參數:會話時鐘時間或自定義時間戳屬性
@durationclass時間間隔或時間點(可為attribute)Null (zero)該標記決定Drools引擎中事件的持續時間
@expiresclass[#d][#h][#m][#s][[ms]]Null (默認時間不在匹配和激活時過期)此標記決定事件在Drools引擎的工作內存中過期之前的時間。默認情況下,當事件不再匹配和激活任何當前規則時,該事件將過期。您可以定義事件過期的時間。這個標記定義還覆蓋了根據時間約束和KIE基中的滑動窗口計算的隱式過期偏移量。只有當Drools引擎以流模式運行時,此標記才可用。
@typesafeclasstrue,falsetrue該標記決定給定的事實類型是否使用類型安全進行編譯。
@serialVersionUIDclassintegerNull序列化ID,考慮到兼容性建議在相關類或DRL文件類型聲明過程中顯式指定serialVersionUID(若未指定則根據類各方面特征自動計算)。
@keyattribute--參與計算equals()和hashCode()的屬性;同時Drools引擎會隱式地定義3個構造函數,分別為無參構造器、全參構造器、附帶@key屬性的構造器。
@positionattributeintegerNone優先級原則:子類>父類;顯式指定>未指定;聲明順序
@classReactiveclass--全局開關處于開啟狀態(默認 ALWAYS),代表屬性響應性生效;可以通過該標記禁用指定類的屬性響應性,實現微調;與ALLOWED對應,每次觸發規則時重新評估事實的所有事實模式。
@propertyReactiveclass--全局開關處于可選狀態(ALLOWED)時,代表屬性響應性停用;可以通過該標記啟用指定類的屬性響應性,實現微調;與ALWAYS對應,僅對給定模式內受約束或綁定的修改屬性做出反應。DISABLED狀態時,所有屬性更改偵聽器都將被忽略(即不重新評估)。
@watchfactPatternProperty name, * (all), ! (not), !* (no properties)None全局開關處于開啟狀態(ALWAYS)或處于可選狀態(ALLOWED)且類被標記為@propertyReactive時,總之,當前類型處于屬性響應性狀態時,你可以使用通配符或非操作過濾屬性;處于非屬性響應性,使用@watch或出現沖突例如@watch( firstName, ! firstName ))時編譯錯誤
@propertyChangeSupportclass--增加該標記,可使drools可以監聽javabean的屬性變動。

下面以典型的電信領域語音呼叫為例

public class VoiceCall {private String originNumber;private String destinationNumber;private Date callDateTime;private long callDuration; // in milliseconds// Constructors, getters, and setters }
  • 類級別元數據
declare VoiceCall@role( event )@timestamp( callDateTime )@duration( callDuration )@expires( 1h35m )@typesafe( false )@serialVersionUID( 42 ) end
  • @key
declare PersonfirstName : String @keylastName : String @keyage : int end
  • @position
declare PersonfirstName : String @position( 1 )lastName : String @position( 0 )age : int @position( 2 )occupation: String enddeclare Student extends Persondegree : String @position( 1 )school : String @position( 0 )graduationDate : Date end
  • @watch
// Listens for changes in both `firstName` (inferred) and `lastName`: Person(firstName == $expectedFirstName) @watch( lastName )// Listens for changes in all properties of the `Person` fact: Person(firstName == $expectedFirstName) @watch( * )// Listens for changes in `lastName` and explicitly excludes changes in `firstName`: Person(firstName == $expectedFirstName) @watch( lastName, !firstName )// Listens for changes in all properties of the `Person` fact except `age`: Person(firstName == $expectedFirstName) @watch( *, !age )// Excludes changes in all properties of the `Person` fact (equivalent to using `@classReactivity` tag): Person(firstName == $expectedFirstName) @watch( !* )
  • @propertyChangeSupport
declare Person@propertyChangeSupport end

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并不使用反射,而是依賴于使用生成的字節碼實現的性能更好的訪問器

參考:

drools官方文檔

未完待續……

總結

以上是生活随笔為你收集整理的drools规则引擎使用文档的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。