drools簡單應用

  當某個服務的需求經常變的時候,如果使用了硬編碼的方式進行開發會是一件非常麻煩的事。

  最近在對項目的積分模塊進行改造的時候想到了規則引擎,使用規則引擎處理復雜而且多變的業務邏輯有其非常大的優勢,包括實時更新、性能等方面。

不多說,直接上代碼:

1、第一步先寫好工具類,有了工具類,只需在應用的業務場景中調用相應方法就可以了

@Component
public class KieSessionUtils {private static KieBase kieBase;//定義規則文件的包名,與drl文件里的package對應private static final String drlPackage = "rules";//定義drl文件的存放路徑,靜態變量需要通過在其set方法上打@Value注解,才可實現配置注入private static String drlPath;//通過配置拉取路徑,這里推薦一下apollo配置中心,使用apollo可以實時更改通過@Value拉取的配置@Value("${drools.points.drlPath}")public void setDrlPath(String drlPath){KieSessionUtils.drlPath = drlPath;}/***  生成kieSeesion會話* @param ruleName* @return* @throws Exception*/public static KieSession newKieSession(String ruleName) throws Exception {//無狀態的kieSession,和有狀態相比,區別在于不維持會話,即使用完后自動釋放資源,不需要手動調dispose//StatelessKieSession kieSession = getKieBase(ruleName).newStatelessKieSession();//有狀態的kieSessionKieSession kieSession = getKieBase(ruleName).newKieSession();//添加監聽器,這里加的是對規則文件運行debug監聽器,測試時最好加上,用于排查問題,生產上可視情況去掉kieSession.addEventListener(new DebugRuleRuntimeEventListener());return kieSession;}/***  生成kieBase* @param ruleName 規則文件名* @return* @throws Exception*/protected static KieBase getKieBase(String ruleName) throws Exception {//判斷kieBase和需要獲取的規則文件是否存在,不存在則重新初始化kieBaseif (kieBase ==null || kieBase.getRule(drlPackage,ruleName)==null) {KieServices kieServices = KieServices.Factory.get();KieFileSystem kfs = kieServices.newKieFileSystem();//獲取規則數據源,這里由于本人項目使用的是springboot,打包會打成jar包,如果想做實時更新,drl文件需要放在jar包外面//獲取resource的方式很多,不一定要用讀取文件的方式,可根據自己的設計和業務場景采取不同方案Resource resource = kieServices.getResources().newFileSystemResource(new File(drlPath+"/"+ruleName));resource.setResourceType(ResourceType.DRL);kfs.write(resource);KieBuilder kieBuilder = kieServices.newKieBuilder(kfs).buildAll();if (kieBuilder.getResults().getMessages(Message.Level.ERROR).size() > 0) {throw new Exception();}KieContainer kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());kieBase = kieContainer.getKieBase();}return kieBase;}/*** 更新規則* @param ruleName 規則名和規則文件名* @throws Exception*/public static void refreshRules(String ruleName) throws Exception {//判斷規則不為null,則移除規則if (kieBase !=null && kieBase.getRule(drlPackage,ruleName)!=null){//為了方便,本人把規則名和drl文件名稱統一定義了
            kieBase.removeRule(drlPackage,ruleName);//重新初始化kieBase
            getKieBase(ruleName);}}
}

2、編寫規則文件,這里只給出和規則引擎格式有關的代碼

package rules;    //包名import com.jiuair.dto.AddObject
import java.util.List
import java.util.HashMap
import java.util.Map
import java.util.ArrayList
import java.util.Date
import java.util.Iterator
import java.util.Setglobal com.demo.dto.AddObject addObject    //傳入的對象,同時也是返回值對象
rule "add.drl"    //規則名,為了方便,設為何drl文件名一樣,可以不一樣
        when$s : AddObject();then。。。。。//這一段加自己業務代碼邏輯,支持jdk$s.setResult(X);    //執行完邏輯后將結果設置到對象中
end

3、在業務場景中調用工具類里的方法

private AddObject executeAddRule(Object data) {AddObject addObject = new AddObject();addObject.setJsonObject(data);try {//獲取會話KieSession kieSession = KieSessionUtils.newKieSession("add.drl");//設置傳入參數
            kieSession.insert(addObject);//設置全局參數kieSession.setGlobal("addObject",addObject);//執行規則
            kieSession.fireAllRules();//釋放會話資源
            kieSession.dispose();} catch (Exception e) {e.printStackTrace();}return addObject;}

4、實現實時更新drl文件

   /*** 更新規則文件,這里只給出service層的代碼了,相信controller大家都會寫。。。* @param name  名稱為drl的文件名* @param is    由于dubbo不支持流的方式傳輸,文件需在controller轉為byte數組,再傳到service*/@Overridepublic void refreshRule(String name, byte[] is) {try {FileOutputStream fos = new FileOutputStream(drlPath+"/"+name);fos.write(is);fos.close();KieSessionUtils.refreshRules(name);} catch (Exception e) {e.printStackTrace();}}

附maven引包:

<properties><runtime.version>7.20.0.Final</runtime.version></properties><dependency><groupId>org.kie</groupId><artifactId>kie-api</artifactId><version>${runtime.version}</version></dependency><dependency><groupId>org.kie</groupId><artifactId>kie-internal</artifactId><version>${runtime.version}</version></dependency><dependency><groupId>org.drools</groupId><artifactId>drools-core</artifactId><version>${runtime.version}</version></dependency>  <dependency><groupId>org.drools</groupId><artifactId>drools-decisiontables</artifactId><version>${runtime.version}</version></dependency>

?

?

import java?詳細X
沒有英漢互譯結果
??請嘗試網頁搜索

轉載于:https://www.cnblogs.com/jagerLan/p/10857004.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/279541.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/279541.shtml
英文地址,請注明出處:http://en.pswp.cn/news/279541.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

31 天重構學習筆記28. 為布爾方法命名

摘要&#xff1a;由于最近在做重構的項目&#xff0c;所以對重構又重新進行了一遍學習和整理&#xff0c;對31天重構最早接觸是在2009年 10月份&#xff0c;由于當時沒有訂閱Sean Chambers的blog&#xff0c;所以是在國外的社區上閑逛的時候鏈接過去的。記得當時一口氣看完了整…

Matplotlib學習---用matplotlib畫誤差線(errorbar)

誤差線用于顯示數據的不確定程度&#xff0c;誤差一般使用標準差&#xff08;Standard Deviation&#xff09;或標準誤差&#xff08;Standard Error&#xff09;。 標準差&#xff08;SD&#xff09;&#xff1a;是方差的算術平方根。如果是總體標準差&#xff0c;那么用σ表示…

關于自增id 你可能還不知道

導讀&#xff1a;在使用MySQL建表時&#xff0c;我們通常會創建一個自增字段(AUTO_INCREMENT)&#xff0c;并以此字段作為主鍵。本篇文章將以問答的形式講述關于自增id的一切。 注&#xff1a; 本文所講的都是基于Innodb存儲引擎。 1.MySQL為什么建議將自增列id設為主鍵&#x…

Android One和Android Go有什么區別?

In 2014, Google announced a lineup of low-cost, low-spec phones called Android One. In 2017, they announced Android Go, specifically designed for low-cost, low-spec phones. So…what’s the difference? 2014年&#xff0c;Google宣布了一系列名為Android One的低…

outlook advanced find 快捷鍵不起作用

癥狀&#xff1a;用戶反應按outlook advanced find的快捷鍵時無效&#xff0c;快捷鍵為CtrlShiftF。第一感覺是肯定跟別的軟件有沖突了&#xff0c;觀察了下&#xff0c;發現用戶正在使用sougou拼音輸入法&#xff0c;于是點其屬性查看&#xff0c;果然發現與其的簡繁切換沖突了…

vue1.0和vue2.0生命周期----整理一

## 1. 作用域區別   1.x 隨意的定義作用域   2.x 不允許body 或者html 元素 ## 2. 生命周期   1.x:     created 實例已經創建     beforeCompile 在編譯之前     compiled 編譯之后     ready 實例已經插入到文檔之中     beforeDetroy 在銷毀之前 …

21-while里的break簡單用法

break是結束循環&#xff0c;break之后、循環體內代碼不再執行。 while True:yn input(Continue(y/n): )if yn in [n,N]:breakprint(running......) 結果輸出&#xff1a; 轉載于:https://www.cnblogs.com/hejianping/p/10861816.html

視頻造假_如何發現“深造假”面部切換視頻

視頻造假Recently, Reddit has been making news again with a subreddit in w hich people use a machine learning tool called “Deep Fake” to automatically replace one person’s face with another in a video. Obviously, since this is the internet, people are us…

C#實現MD5加密

C#實現MD5加密。 1、創建MD5Str.cs加密處理類 [csharp] view plaincopy public class MD5Str { /// <summary> /// 字符串MD5加密 /// </summary> /// <param name"Text">要加密的字符串</param> /// <returns…

【agc004f】Namori Grundy

那個問一下有人可以解釋以下這個做法嘛&#xff0c;看不太懂QwQ~ Description 有一個n個點n條邊的有向圖&#xff0c;點的編號為從1到n。 給出一個數組p&#xff0c;表明有&#xff08;p1&#xff0c;1&#xff09;&#xff0c;&#xff08;p2&#xff0c;2&#xff09;&#x…

找到特定ip地址 修改ip_您如何找到網站的IP地址?

找到特定ip地址 修改ipWhether you are in it just for a bit of geeky fun, or are seriously wanting to know the answer, how do you find out the IP address for a website? Today’s SuperUser Q&A post looks at the answer, and how to know if more than one we…

Rational Rose 2003 下載、破解及安裝方法(圖文)

方法一&#xff1a; 1、安裝Rational Rose2003時&#xff0c;在需選擇安裝項的時候&#xff0c;只選擇Rational Rose EnterPrise Edition即可&#xff0c;不需選擇其他項&#xff0c;之后選擇“DeskTop Installation from CD Image“&#xff0c;一路下一步。出現Mem_pointer_B…

數據結構:莫隊

莫隊算法是用來處理一類無修改的離線區間詢問問題 莫隊的精髓就在于&#xff0c;離線得到了一堆需要處理的區間后&#xff0c;合理的安排這些區間計算的次序以得到一個較優的復雜度 代表題目是BZOJ2038這道題 進行區間詢問[l,r]&#xff0c;輸出該區間內隨機抽兩次抽到相同顏色…

【學習筆記】第三章 python3核心技術與實踐--Jupyter Notebook

可能你已經知道&#xff0c;Python 在 14 年后的“崛起”&#xff0c;得益于機器學習和數學統計應用的興起。那為什么 Python 如此適合數學統計和機器學習呢&#xff1f;作為“老司機”的我可以肯定地告訴你&#xff0c;Jupyter Notebook &#xff08;https://jupyter.org/&…

二進制安位處理_處理器與安??全性之間的聯系是什么?

二進制安位處理Newer processors are able to contribute to the security of your system, but what exactly do they do to help? Today’s Super User Q&A post looks at the link between processors and system security. 較新的處理器能夠為您的系統安全做出貢獻&am…

李開復現身說法成功的十個啟發

http://blog.sina.com.cn/kaifulee自信不失謙虛&#xff0c;謙虛不失自信天賦就是興趣 興趣就是天賦思考比傳道重要 觀點比解惑重要我不同意你 但我支持你挫折不是懲罰 而是學習的機會創新不重要 有用的創新才重要完美的工作 成長興趣 影響力用勇氣改變可以改變的事情做最好的領…

關于width: 100%的一些看法

一.position對width 設置為百分比的影響<html><head><style type"text/css">img {width: 50%}body {margin: 8px;}</style> </head><body><div style" min-height: 10px; background: red; "><div><im…

Haproxy+多臺MySQL從服務器(Slave) 實現負載均衡

本系統采用MySQL一主多從模式設計&#xff0c;即1臺 MySQL“主”服務器(Master)多臺“從”服務器(Slave)&#xff0c;“從”服務器之間通過Haproxy進行負載均衡&#xff0c;對外只提供一個訪問IP&#xff0c;當程序需要訪問多臺"從"服務器時&#xff0c;只需要訪問Ha…

愛普生第三方相機_值得購買第三方相機鏡頭嗎?

愛普生第三方相機When people buy a Canon or Nikon camera, they often assume that they can only buy Canon or Nikon lenses. But that isn’t true. While Nikon lenses won’t work on your Canon camera, there are third-party lens manufacturers—such as Sigma, Tam…

[BZOJ4182]Shopping

description 權限題。 樹上\(n\)個節點每個節點都有一種物品&#xff0c;每種物品有其價值&#xff0c;價格&#xff0c;數量&#xff0c;只能買一個連通塊中的物品&#xff0c;求\(m\)元能買到物品價值的最大值。 data range \[ n\le 500,m\le 4000,T\le 5,c_i\le m\] solutio…