規(guī)則引擎集合相關(guān)處理
在實(shí)際生產(chǎn)過(guò)程中,有很多關(guān)于集合的處理場(chǎng)景,比如一個(gè)Fact對(duì)象中包含有一個(gè)集合,而需要判斷該集合是否包含某個(gè)值。而Drools規(guī)則引擎也提供了多種處理方式,比如通過(guò)from、contains、exists等進(jìn)行操作,比較。
當(dāng)然也可以通過(guò)function函數(shù)來(lái)做相應(yīng)的比較,在個(gè)在其他章節(jié)講到過(guò),就不在此贅述。下面重點(diǎn)以幾個(gè)實(shí)例才進(jìn)行講解,在具體實(shí)踐中根據(jù)具體情況來(lái)進(jìn)行運(yùn)用。
實(shí)例
省略掉基本的配置,直接看調(diào)用代碼和規(guī)則代碼。
測(cè)試調(diào)用代碼:
public class ContainsDemo extends BaseDemo {
public static void main(String[] args) {
KieSession kieSession = getKieSession("containsVar");
Corporation corporation = new Corporation();
Set<Scope> scopes = new HashSet<>();
scopes.add(new Scope("P2P"));
scopes.add(new Scope("金融"));
scopes.add(new Scope("區(qū)塊鏈"));
corporation.setScopes(scopes);
Scope scope = new Scope("區(qū)塊鏈");
kieSession.insert(corporation);
kieSession.insert(scope);
kieSession.fireAllRules();
}
}
相關(guān)實(shí)體類:
@Data
public class Corporation {
private Set<Scope> scopes;
}
@Data
public class Scope {
public Scope(String scope){
this.scope = scope;
}
private String scope;
}
然后看一下規(guī)則處理:
package com.containsVar
import com.secbro2.drools.entity.Corporation
import com.secbro2.drools.entity.Scope
import java.util.List
rule "containsVar1"
when
$c: Corporation($scopes:scopes);
$s: Scope(scope == "P2P") from $scopes;
then
System.out.println("containsVar1行業(yè)類型為:P2P");
end
rule "containsVar2"
when
$c: Corporation($scopes:scopes);
exists (Scope(scope == "P2P") from $scopes);
then
System.out.println("containsVar2行業(yè)類型為:P2P");
end
rule "containsVar3"
when
$s: Scope(scope == "區(qū)塊鏈")
$c: Corporation(scopes contains $s);
then
System.out.println("containsVar3行業(yè)類型為:區(qū)塊鏈");
end
rule "containsVar4"
when
$s: Scope(scope == "區(qū)塊鏈")
exists (Corporation(scopes contains $s));
then
System.out.println("containsVar4行業(yè)類型為:區(qū)塊鏈");
end
在上述實(shí)例中列舉了4中使用方法:
第一種,首先獲取Fact對(duì)象Corporation,并重新定義了它的屬性scopes。然后,通過(guò)from關(guān)鍵字來(lái)遍歷 scopes。然后,通過(guò)from關(guān)鍵字來(lái)遍歷scopes。然后,通過(guò)from關(guān)鍵字來(lái)遍歷scopes中的值,獲得符合條件的。此時(shí)并不需要傳入Scope對(duì)應(yīng)的fact對(duì)象。
第二種,前半部分同第一種方式,是不過(guò)沒有獲取篩選的結(jié)果,直接用exists來(lái)判斷是否存在。
第三種,先獲得滿足條件的Scope的Fact對(duì)象,然后再利用此fact對(duì)Corporation的fact對(duì)象進(jìn)行篩選,只有滿足條件才可以繼續(xù)。
第四種,與第三種效果相同,原理同第二種方式的exists使用。
本站文章版權(quán)歸原作者及原出處所有 。內(nèi)容為作者個(gè)人觀點(diǎn), 并不代表本站贊同其觀點(diǎn)和對(duì)其真實(shí)性負(fù)責(zé),本站只提供參考并不構(gòu)成任何投資及應(yīng)用建議。本站是一個(gè)個(gè)人學(xué)習(xí)交流的平臺(tái),網(wǎng)站上部分文章為轉(zhuǎn)載,并不用于任何商業(yè)目的,我們已經(jīng)盡可能的對(duì)作者和來(lái)源進(jìn)行了通告,但是能力有限或疏忽,造成漏登,請(qǐng)及時(shí)聯(lián)系我們,我們將根據(jù)著作權(quán)人的要求,立即更正或者刪除有關(guān)內(nèi)容。本站擁有對(duì)此聲明的最終解釋權(quán)。