SpringBoot整合Drools規(guī)則引擎動態(tài)生成業(yè)務(wù)規(guī)則的實(shí)現(xiàn)
????? 最近的項(xiàng)目中,使用的是flowable工作流來處理業(yè)務(wù)流程,但是在業(yè)務(wù)規(guī)則的配置中,是在代碼中直接固定寫死的,領(lǐng)導(dǎo)說這樣不好,需要規(guī)則可以動態(tài)變化,可以通過頁面去動態(tài)配置改變,所以就花了幾天時(shí)間去研究了一下Drools規(guī)則引擎框架。然后應(yīng)用到了項(xiàng)目中。
首先在項(xiàng)目中引入規(guī)則引擎相關(guān)依賴
<properties>
<java.version>1.8</java.version>
<drools.version>7.20.0.Final</drools.version>
</properties>
<dependencies>
<!--引入規(guī)則引擎-->
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-spring</artifactId>
<version>${drools.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-compiler</artifactId>
<version>${drools.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
<version>1.18.20</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
這里的drools版本使用的是7.20.0.Final,如果想和Flowable結(jié)合使用,在流程畫圖中插入規(guī)則任務(wù),可以將drools版本和flowable starter中管理的drools版本 一致,比如我現(xiàn)在的項(xiàng)目中用到的

flowable-srping-boot-starter的依賴版本是6.5.0,點(diǎn)進(jìn)去這個(gè)jar包的pom文件?

?再進(jìn)一步點(diǎn)parent標(biāo)簽

然后再點(diǎn)parent標(biāo)簽的依賴

然后再點(diǎn)parent標(biāo)簽內(nèi)的flowable-root,然后搜索drools

可以看到flowable starter集成管理的drools版本是7.6.0-Final,所以最好和這個(gè)版本保持一致
當(dāng)然你需要在flowable modeler畫圖項(xiàng)目中引入,然后啟動flowable modeler程序,在畫圖界面

?任務(wù)類型中就可以看到一個(gè)Business rule task,商業(yè)規(guī)則任務(wù)。?
如果只是獨(dú)立使用,則可以直接使用我最開始引入的那個(gè)版本7.20.0.Final
還有一個(gè)問題就是如果你的項(xiàng)目中引入了spring boot的熱部署工具,?
?
需要把這個(gè)依賴注釋掉,項(xiàng)目中不能引入這個(gè)jar包,不然這個(gè)jar包會影響drools規(guī)則引擎執(zhí)行生成的規(guī)則,而且在運(yùn)行規(guī)則的時(shí)候也不會報(bào)錯(cuò),這是個(gè)很隱蔽的坑,我在項(xiàng)目中已經(jīng)踩過坑了,所以特別提示一下,就是這個(gè)jar包存在,規(guī)則引擎在觸發(fā)執(zhí)行規(guī)則的時(shí)候,是?不會執(zhí)行的,在日志信息中一直顯示的是執(zhí)行規(guī)則0條,即使你的規(guī)則文件語法沒有任何錯(cuò)誤,直接將這個(gè)依賴刪除后,就可以正常執(zhí)行規(guī)則了。
引入相關(guān)依賴后,需要在項(xiàng)目中添加配置類:
在config包下創(chuàng)建DroolsAutoConfiguration類
import cn.hutool.core.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.*;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.kie.spring.KModuleBeanFactoryPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.io.IOException;
/**
* @author xiaomifeng1010
* @version 1.0
* @date: 2021/12/6 9:30
* @Description drools配置類
*/
@Configuration
@Slf4j
public class DroolsAutoConfiguration {
public static final String RULE_PATH="rules/";
public KieServices getKieServices(){
KieServices kieServices = KieServices.Factory.get();
return kieServices;
}
/**
* 管理規(guī)則文件的位置路徑信息
* @return
* @throws IOException
*/
@Bean
@ConditionalOnMissingBean(KieFileSystem.class)
public KieFileSystem kieFileSystem() throws IOException {
KieFileSystem kieFileSystem = getKieServices().newKieFileSystem();
for (Resource file:getRuleFiles()) {
kieFileSystem.write(ResourceFactory.newClassPathResource(RULE_PATH+file.getFilename(), CharsetUtil.UTF_8));
}
return kieFileSystem;
}
@Bean
@ConditionalOnMissingBean(KieContainer.class)
public KieContainer kieContainer() throws IOException {
KieServices kieServices = getKieServices();
KieRepository kieRepository = kieServices.getRepository();
kieRepository.addKieModule(new KieModule() {
@Override
public ReleaseId getReleaseId() {
return kieRepository.getDefaultReleaseId();
}
});
KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem());
kieBuilder.buildAll();
Results results = kieBuilder.getResults();
if (results.hasMessages(Message.Level.ERROR)){
log.error(results.getMessages().toString());
}
KieContainer kieContainer = kieServices.newKieContainer(kieRepository.getDefaultReleaseId());
return kieContainer;
}
@Bean
@ConditionalOnMissingBean(KieBase.class)
public KieBase kieBase() throws IOException {
KieBase kieBase = kieContainer().getKieBase();
return kieBase;
}
@Bean
@ConditionalOnMissingBean(KieSession.class)
public KieSession kieSession() throws IOException {
return kieContainer().newKieSession();
}
@Bean
@ConditionalOnMissingBean(KModuleBeanFactoryPostProcessor.class)
public KModuleBeanFactoryPostProcessor kModuleBeanFactoryPostProcessor(){
KModuleBeanFactoryPostProcessor kModuleBeanFactoryPostProcessor = new KModuleBeanFactoryPostProcessor();
return kModuleBeanFactoryPostProcessor;
}
/**
* 獲取規(guī)則文件資源
* @return
* @throws IOException
*/
private Resource[] getRuleFiles() throws IOException {
ResourcePatternResolver resourcePatternResolver
=new PathMatchingResourcePatternResolver();
Resource[] resources = resourcePatternResolver.getResources("classpath*:" + RULE_PATH + "**/*.*");
return resources;
}
}
然后在項(xiàng)目的resources下創(chuàng)建rules文件夾存放規(guī)則文件

?創(chuàng)建一個(gè)drl后綴的規(guī)則文件FixRateCostCalculatorRule.drl
//package 可以隨意指定,沒有具體的要求,可以命名成和項(xiàng)目相關(guān)的,或者直接rules
package com.drools
//或者這樣
//package rules
import java.math.BigDecimal
import java.lang.Integer
import org.apache.commons.lang3.math.NumberUtils;
import com.drools.bo.GuatanteeCost
//這里設(shè)置的全局變量只相當(dāng)于聲明變量,需要在代碼執(zhí)行規(guī)則前給該變量賦值初始化
global org.slf4j.Logger logger
rule "rule1"
//dialect "java"
salience 30
//防止死循環(huán)
//no-loop true
enabled false
when
$guaranteeCost:GuatanteeCost(amount>NumberUtils.DOUBLE_ZERO && amount<=300000)
then
$guaranteeCost.setCost(200d);
logger.info("保費(fèi)"+200);
update($guaranteeCost)
end
rule "rule2"
enabled false
salience 20
when
$guaranteeCost:GuatanteeCost(amount>300000,amount<=500000)
then
$guaranteeCost.setCost(300d);
logger.info("保費(fèi)"+300);
update($guaranteeCost)
end
rule "rule3"
enabled false
salience 10
when
$guaranteeCost:GuatanteeCost(amount>500000,amount<=800000)
then
// 效果和上邊兩條范圍中的更新數(shù)據(jù)效果一樣
modify($guaranteeCost){
setCost(400d)
}
logger.info("保費(fèi)"+400);
end
然后需要?jiǎng)?chuàng)建一個(gè)java對象GuatanteeCost,用于向規(guī)則文件中傳遞Fact(java對象)變量值
amount是GuatanteeCost類中的屬性
@Data
@NoArgsConstructor
@AllArgsConstructor
public class GuatanteeCost {
/**
* 保證金金額
*/
private Double amount;
/**
* 保費(fèi)金額
*/
private Double cost;
}
然后就可以寫一個(gè)單元測試方法,或者創(chuàng)建一個(gè)controller進(jìn)行測試
import cn.hutool.core.util.CharsetUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.drools.bo.GuatanteeCost;
import com.drools.entity.DroolsRuleConfig;
import com.drools.service.DroolsRuleConfigService;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.drools.template.ObjectDataCompiler;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.kie.internal.utils.KieHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
/**
* @author xiaomifeng1010
* @version 1.0
* @date: 2021/12/6 15:41
* @Description
*/
@RestController
@RequestMapping("/drools")
@AllArgsConstructor(onConstructor_={@Autowired})
@Api(tags = "drools規(guī)則引擎測試接口")
@ApiSort(30)
@Slf4j
public class DroolsTestController {
@Autowired
private KieSession kieSession;
@Autowired
private DroolsRuleConfigService droolsRuleConfigService;
@ApiOperation("測試計(jì)算保費(fèi)規(guī)則")
@ApiImplicitParam(name="bzjAmount",value = "保證金金額(單位元)")
@PostMapping("test/rule")
public String testDrools(BigDecimal bzjAmount){
GuatanteeCost guatanteeCost = new GuatanteeCost();
guatanteeCost.setAmount(bzjAmount.doubleValue());
kieSession.insert(guatanteeCost);
kieSession.setGlobal("logger",log);
int allRules = kieSession.fireAllRules();
Double cost = guatanteeCost.getCost();
log.info("成功執(zhí)行{}條規(guī)則",allRules);
log.info("計(jì)算保費(fèi){}元", cost);
kieSession.dispose();
return cost+"";
}
@ApiOperation("測試使用規(guī)則模板計(jì)算保費(fèi)規(guī)則")
@ApiImplicitParam(name="bzjAmount",value = "保證金金額(單位元)")
@PostMapping("test/ruleTemplate")
public String testDroolsRuleTemplate(BigDecimal bzjAmount){
GuatanteeCost guatanteeCost = new GuatanteeCost();
guatanteeCost.setAmount(bzjAmount.doubleValue());
List<DroolsRuleConfig> droolsRuleConfigList = droolsRuleConfigService.list(Wrappers.<DroolsRuleConfig>lambdaQuery()
.eq(DroolsRuleConfig::getRuleName, "fix"));
ObjectDataCompiler converter = new ObjectDataCompiler();
String drlContent = StringUtils.EMPTY;
try(InputStream dis= ResourceFactory.
newClassPathResource("rules/FixRateCostCalculatorRule.drt", CharsetUtil.UTF_8)
.getInputStream()){
// 填充模板內(nèi)容
drlContent=converter.compile(droolsRuleConfigList, dis);
log.info("生成的規(guī)則內(nèi)容:{}",drlContent);
}catch (IOException e) {
log.error("獲取規(guī)則模板文件出錯(cuò):{}",e.getMessage());
}
KieHelper helper = new KieHelper();
helper.addContent(drlContent, ResourceType.DRL);
KieSession ks = helper.build().newKieSession();
ks.insert(guatanteeCost);
// kieSession.setGlobal("logger",log);
int allRules = ks.fireAllRules();
Double cost = guatanteeCost.getCost();
log.info("成功執(zhí)行{}條規(guī)則",allRules);
log.info("計(jì)算保費(fèi){}元", cost);
kieSession.dispose();
return cost+"";
}
}

至此,可以先忽視第二個(gè)接口方法,使用第一個(gè)接口方法來測試規(guī)則的運(yùn)行

計(jì)算的費(fèi)用是200,執(zhí)行的是rule1規(guī)則,200000介于0-300000之間,所以保費(fèi)計(jì)算的是200

這種直接寫drl規(guī)則文件,在里邊設(shè)定規(guī)則的方式比較簡便,但是卻不靈活,如果我想再添加幾條范圍,那么就需要重新再來修改這個(gè)drl文件,所以在項(xiàng)目中可以使用規(guī)則模板drt
然后在項(xiàng)目resources的rules目錄下再創(chuàng)建一個(gè)drt文件FixRateCostCalculatorRule.drt
//模板文件
template header
min
max
fixedFee
package drools.templates
import com.drools.bo.GuatanteeCost
template "fixRate"
rule "calculate rule_@{row.rowNumber}"
dialect "mvel"
no-loop true
when
$guaranteeCost:GuatanteeCost(amount>@{min} && amount<=@{max})
then
modify($guaranteeCost){
setCost(@{fixedFee})
}
end
end template
然后創(chuàng)建一個(gè)表,用于保存min,max和fixed的參數(shù)值(注意事項(xiàng):template header下邊的min,max和fixedFee都相當(dāng)于聲明的參數(shù),但是不能在min上邊加一行注釋如://參數(shù)說明,在解析規(guī)則模板時(shí)候會把“//參數(shù)說明”也當(dāng)做聲明的參數(shù)變量),因?yàn)檫@些值可以動態(tài)變化了,所以范圍規(guī)則也相當(dāng)于可以動態(tài)變化,范圍就不是之前設(shè)置的固定的啦

?創(chuàng)建這樣一個(gè)表,這樣就可以靈活配置范圍和保費(fèi)金額了
CREATE TABLE `biz_drools_rule_config` ( `id` bigint(20) NOT NULL, `rule_code` varchar(255) DEFAULT NULL COMMENT '規(guī)則編碼', `rule_name` varchar(255) DEFAULT NULL COMMENT '規(guī)則名稱', `min` int(10) DEFAULT NULL COMMENT '保證金范圍最小值', `max` int(10) DEFAULT NULL COMMENT '保證金范圍最大值', `fixed_fee` decimal(10,2) DEFAULT NULL COMMENT '固定保費(fèi)', `fee_rate` decimal(5,3) DEFAULT NULL COMMENT '費(fèi)率(小數(shù))', `create_by` varchar(25) DEFAULT NULL, `create_time` datetime DEFAULT NULL, `update_by` varchar(25) DEFAULT NULL, `update_time` datetime DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;
?然后創(chuàng)建對應(yīng)的實(shí)體類,mapper和service,可以使用項(xiàng)目中的代碼生成器快捷生成或者idea的插件生成
然后就可以使用controller中的第二個(gè)接口方法來測試了
數(shù)據(jù)庫中的數(shù)據(jù)插入,可以在項(xiàng)目頁面中寫一個(gè)用于添加規(guī)則配置參數(shù)的頁面,在里邊插入幾條數(shù)

這里我是先隨意手動添加了幾條數(shù)據(jù)
?然后在knife4j文檔頁面執(zhí)行接口測試

加上oauth2的驗(yàn)證信息

?輸入amount的值,也計(jì)算的固定保費(fèi)200
同時(shí)從數(shù)據(jù)庫中查詢出來3條數(shù)據(jù),對應(yīng)三個(gè)范圍,生成了三個(gè)規(guī)則(rule),可以從項(xiàng)目日志中查看


此時(shí)可以把數(shù)據(jù)庫中的最大最小值改變一下,再測試一下

此時(shí)再傳入一個(gè)保證金amount值20萬,就會計(jì)算出保費(fèi)費(fèi)用是300元?,執(zhí)行代碼時(shí),會再次生成新的規(guī)則,每次執(zhí)行規(guī)則模板動態(tài)生成的規(guī)則drl內(nèi)容實(shí)際上保存在內(nèi)存中的,并不像最開始創(chuàng)建的drl文件那樣

再次執(zhí)行,就會發(fā)現(xiàn)保費(fèi)計(jì)算就成了300元

?同時(shí)規(guī)則模板動態(tài)生成的規(guī)則內(nèi)容也對應(yīng)發(fā)生了變化

為了方便使用這個(gè)規(guī)則模板,可以將測試規(guī)則模板的這個(gè)接口方法封裝成一個(gè)輔助類,在業(yè)務(wù)使用時(shí),可以直接調(diào)用
package com.drools.util;
import cn.hutool.core.util.CharsetUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.drools.bo.GuatanteeCost;
import com.drools.entity.DroolsRuleConfig;
import com.drools.service.DroolsRuleConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.drools.template.ObjectDataCompiler;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.kie.internal.utils.KieHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
/**
* @author xiaomifeng1010
* @version 1.0
* @date: 2021/12/8 16:22
* @Description 根據(jù)規(guī)則引擎模板獲取保費(fèi)金額
*/
@Component
@Slf4j
public class CalculateCostUtil {
@Autowired
private DroolsRuleConfigService droolsRuleConfigService;
/**
* @description: 獲取固定保費(fèi)
* @author: xiaomifeng1010
* @date: 2021/12/8
* @param bzjAmount
* @return: BigDecimal
**/
public BigDecimal getFixedFee(BigDecimal bzjAmount){
GuatanteeCost guatanteeCost = new GuatanteeCost();
guatanteeCost.setAmount(bzjAmount.doubleValue());
List<DroolsRuleConfig> droolsRuleConfigList = droolsRuleConfigService.list(Wrappers.<DroolsRuleConfig>lambdaQuery()
.eq(DroolsRuleConfig::getRuleName, "fix"));
ObjectDataCompiler converter = new ObjectDataCompiler();
String drlContent = StringUtils.EMPTY;
try(InputStream dis= ResourceFactory.
newClassPathResource("rules/FixRateCostCalculatorRule.drt", CharsetUtil.UTF_8)
.getInputStream()){
// 填充模板內(nèi)容
drlContent=converter.compile(droolsRuleConfigList, dis);
log.info("生成的規(guī)則內(nèi)容:{}",drlContent);
}catch (IOException e) {
log.error("獲取規(guī)則模板文件出錯(cuò):{}",e.getMessage());
}
KieHelper helper = new KieHelper();
helper.addContent(drlContent, ResourceType.DRL);
KieSession ks = helper.build().newKieSession();
ks.insert(guatanteeCost);
int allRules = ks.fireAllRules();
Double cost = guatanteeCost.getCost();
log.info("成功執(zhí)行{}條規(guī)則",allRules);
log.info("計(jì)算保費(fèi){}元", cost);
ks.dispose();
return BigDecimal.valueOf(cost);
}
}
暫時(shí)就研究了這些點(diǎn)東西,算是剛剛?cè)腴T這個(gè)框架,買的drools圖書,還得再多讀幾遍,多實(shí)踐操作一下,以后再做一些更深入的總結(jié)?
到此這篇關(guān)于SpringBoot整合Drools規(guī)則引擎動態(tài)生成業(yè)務(wù)規(guī)則的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)SpringBoot整合Drools生成業(yè)務(wù)規(guī)則內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot實(shí)現(xiàn)釘釘機(jī)器人消息推送的示例代碼
這篇文章主要介紹了SpringBoot實(shí)現(xiàn)釘釘機(jī)器人消息推送的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
IDEA的部署設(shè)置改為war exploded運(yùn)行項(xiàng)目出錯(cuò)問題
在使用IDEA配置warexploded部署時(shí),可能會遇到路徑問題或404錯(cuò)誤,解決方法是進(jìn)入Deployment設(shè)置,刪除Application content中的/marry_war_exploded,使其為空,然后重新運(yùn)行項(xiàng)目即可,這是一種有效的解決策略,希望能幫助到遇到同樣問題的開發(fā)者2024-10-10
Java Socket報(bào)錯(cuò)打開文件過多的問題
這篇文章主要介紹了Java Socket報(bào)錯(cuò)打開文件過多的問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
MyBatis實(shí)現(xiàn)動態(tài)SQL更新的代碼示例
本文博小編將帶領(lǐng)大家學(xué)習(xí)如何利用 MyBatis 攔截器機(jī)制來優(yōu)雅的實(shí)現(xiàn)這個(gè)需求,文中通過代碼示例介紹的非常詳細(xì),具有一定的參考價(jià)值,需要的朋友可以參考下2023-07-07
SpringBoot修改yml配置和加載順序規(guī)則的示例詳解
這篇文章主要為大家詳細(xì)介紹了SpringBoot如何修改yml配置和加載順序規(guī)則,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-08-08

