100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > SpringBoot整合Drools规则引擎动态生成业务规则

SpringBoot整合Drools规则引擎动态生成业务规则

时间:2020-06-30 10:18:41

相关推荐

SpringBoot整合Drools规则引擎动态生成业务规则

最近的项目中,使用的是flowable工作流来处理业务流程,但是在业务规则的配置中,是在代码中直接固定写死的,领导说这样不好,需要规则可以动态变化,可以通过页面去动态配置改变,所以就花了几天时间去研究了一下Drools规则引擎框架。然后应用到了项目中。

首先在项目中引入规则引擎相关依赖

<properties><java.version>1.8</java.version><drools.version>7.20.0.Final</drools.version></properties><dependencies><!--引入规则引擎--><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结合使用,在流程画图中插入规则任务,可以将drools版本和flowable starter中管理的drools版本 一致,比如我现在的项目中用到的

flowable-srping-boot-starter的依赖版本是6.5.0,点进去这个jar包的pom文件

再进一步点parent标签

然后再点parent标签的依赖

然后再点parent标签内的flowable-root,然后搜索drools

可以看到flowable starter集成管理的drools版本是7.6.0-Final,所以最好和这个版本保持一致

当然你需要在flowable modeler画图项目中引入,然后启动flowable modeler程序,在画图界面

任务类型中就可以看到一个Business rule task,商业规则任务。

如果只是独立使用,则可以直接使用我最开始引入的那个版本7.20.0.Final

还有一个问题就是如果你的项目中引入了spring boot的热部署工具,

需要把这个依赖注释掉,项目中不能引入这个jar包,不然这个jar包会影响drools规则引擎执行生成的规则,而且在运行规则的时候也不会报错,这是个很隐蔽的坑,我在项目中已经踩过坑了,所以特别提示一下,就是这个jar包存在,规则引擎在触发执行规则的时候,是不会执行的,在日志信息中一直显示的是执行规则0条,即使你的规则文件语法没有任何错误,直接将这个依赖删除后,就可以正常执行规则了。

引入相关依赖后,需要在项目中添加配置类:

在config包下创建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: /12/6 9:30* @Description drools配置类*/@Configuration@Slf4jpublic class DroolsAutoConfiguration {public static final String RULE_PATH="rules/";public KieServices getKieServices(){KieServices kieServices = KieServices.Factory.get();return kieServices;}/*** 管理规则文件的位置路径信息* @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() {@Overridepublic 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;}/*** 获取规则文件资源* @return* @throws IOException*/private Resource[] getRuleFiles() throws IOException {ResourcePatternResolver resourcePatternResolver=new PathMatchingResourcePatternResolver();Resource[] resources = resourcePatternResolver.getResources("classpath*:" + RULE_PATH + "**/*.*");return resources;}}

然后在项目的resources下创建rules文件夹存放规则文件

创建一个drl后缀的规则文件FixRateCostCalculatorRule.drl

//package 可以随意指定,没有具体的要求,可以命名成和项目相关的,或者直接rulespackage com.drools//或者这样//package rulesimport java.math.BigDecimalimport java.lang.Integerimport mons.lang3.math.NumberUtils;import com.drools.bo.GuatanteeCost//这里设置的全局变量只相当于声明变量,需要在代码执行规则前给该变量赋值初始化global org.slf4j.Logger loggerrule "rule1"//dialect "java"salience 30//防止死循环//no-loop trueenabled falsewhen$guaranteeCost:GuatanteeCost(amount>NumberUtils.DOUBLE_ZERO && amount<=300000)then$guaranteeCost.setCost(200d);logger.info("保费"+200);update($guaranteeCost)endrule "rule2"enabled falsesalience 20when$guaranteeCost:GuatanteeCost(amount>300000,amount<=500000)then$guaranteeCost.setCost(300d);logger.info("保费"+300);update($guaranteeCost)endrule "rule3"enabled falsesalience 10when$guaranteeCost:GuatanteeCost(amount>500000,amount<=800000)then// 效果和上边两条范围中的更新数据效果一样modify($guaranteeCost){setCost(400d)}logger.info("保费"+400);end

然后需要创建一个java对象GuatanteeCost,用于向规则文件中传递Fact(java对象)变量值

amount是GuatanteeCost类中的属性

@Data@NoArgsConstructor@AllArgsConstructorpublic class GuatanteeCost {/*** 保证金金额*/private Double amount;/*** 保费金额*/private Double cost;}

然后就可以写一个单元测试方法,或者创建一个controller进行测试

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 mons.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: /12/6 15:41* @Description*/@RestController@RequestMapping("/drools")@AllArgsConstructor(onConstructor_={@Autowired})@Api(tags = "drools规则引擎测试接口")@ApiSort(30)@Slf4jpublic class DroolsTestController {@Autowiredprivate KieSession kieSession;@Autowiredprivate DroolsRuleConfigService droolsRuleConfigService;@ApiOperation("测试计算保费规则")@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("成功执行{}条规则",allRules);log.info("计算保费{}元", cost);kieSession.dispose();return cost+"";}@ApiOperation("测试使用规则模板计算保费规则")@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()){// 填充模板内容drlContent=pile(droolsRuleConfigList, dis);log.info("生成的规则内容:{}",drlContent);}catch (IOException e) {log.error("获取规则模板文件出错:{}",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("成功执行{}条规则",allRules);log.info("计算保费{}元", cost);kieSession.dispose();return cost+"";}}

至此,可以先忽视第二个接口方法,使用第一个接口方法来测试规则的运行

计算的费用是200,执行的是rule1规则,200000介于0-300000之间,所以保费计算的是200

这种直接写drl规则文件,在里边设定规则的方式比较简便,但是却不灵活,如果我想再添加几条范围,那么就需要重新再来修改这个drl文件,所以在项目中可以使用规则模板drt

然后在项目resources的rules目录下再创建一个drt文件FixRateCostCalculatorRule.drt

//模板文件template headerminmaxfixedFeepackage drools.templatesimport com.drools.bo.GuatanteeCosttemplate "fixRate"rule "calculate rule_@{row.rowNumber}"dialect "mvel"no-loop truewhen$guaranteeCost:GuatanteeCost(amount>@{min} && amount<=@{max})thenmodify($guaranteeCost){setCost(@{fixedFee})}endend template

然后创建一个表,用于保存min,max和fixed的参数值(注意事项:template header下边的min,max和fixedFee都相当于声明的参数,但是不能在min上边加一行注释如://参数说明,在解析规则模板时候会把“//参数说明”也当做声明的参数变量),因为这些值可以动态变化了,所以范围规则也相当于可以动态变化,范围就不是之前设置的固定的啦

创建这样一个表,这样就可以灵活配置范围和保费金额了

CREATE TABLE `biz_drools_rule_config` (`id` bigint(20) NOT NULL,`rule_code` varchar(255) DEFAULT NULL COMMENT '规则编码',`rule_name` varchar(255) DEFAULT NULL COMMENT '规则名称',`min` int(10) DEFAULT NULL COMMENT '保证金范围最小值',`max` int(10) DEFAULT NULL COMMENT '保证金范围最大值',`fixed_fee` decimal(10,2) DEFAULT NULL COMMENT '固定保费',`fee_rate` decimal(5,3) DEFAULT NULL COMMENT '费率(小数)',`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;

然后创建对应的实体类,mapper和service,可以使用项目中的代码生成器快捷生成或者idea的插件生成

然后就可以使用controller中的第二个接口方法来测试了

数据库中的数据插入,可以在项目页面中写一个用于添加规则配置参数的页面,在里边插入几条数

这里我是先随意手动添加了几条数据

然后在knife4j文档页面执行接口测试

加上oauth2的验证信息

输入amount的值,也计算的固定保费200

同时从数据库中查询出来3条数据,对应三个范围,生成了三个规则(rule),可以从项目日志中查看

此时可以把数据库中的最大最小值改变一下,再测试一下

此时再传入一个保证金amount值20万,就会计算出保费费用是300元,执行代码时,会再次生成新的规则,每次执行规则模板动态生成的规则drl内容实际上保存在内存中的,并不像最开始创建的drl文件那样

再次执行,就会发现保费计算就成了300元

同时规则模板动态生成的规则内容也对应发生了变化

为了方便使用这个规则模板,可以将测试规则模板的这个接口方法封装成一个辅助类,在业务使用时,可以直接调用

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 mons.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.ponent;import java.io.IOException;import java.io.InputStream;import java.math.BigDecimal;import java.util.List;/*** @author xiaomifeng1010* @version 1.0* @date: /12/8 16:22* @Description 根据规则引擎模板获取保费金额*/@Component@Slf4jpublic class CalculateCostUtil {@Autowiredprivate DroolsRuleConfigService droolsRuleConfigService;/*** @description: 获取固定保费* @author: xiaomifeng1010* @date: /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()){// 填充模板内容drlContent=pile(droolsRuleConfigList, dis);log.info("生成的规则内容:{}",drlContent);}catch (IOException e) {log.error("获取规则模板文件出错:{}",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("成功执行{}条规则",allRules);log.info("计算保费{}元", cost);ks.dispose();return BigDecimal.valueOf(cost);}}

暂时就研究了这些点东西,算是刚刚入门这个框架,买的drools图书,还得再多读几遍,多实践操作一下,以后再做一些更深入的总结

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。