文章目录
- 一、使用
- 1、参考资料
- 2、引包
- 3、创建规则实体类
- 4、实现drools动态规则
- 5、模拟数据库,实现规则的CRUD
- 6、创建控制层
- 7、测试规则的动态添加
- (1)添加规则
- (2)修改规则
- (3)删除规则
- 8、模拟2个kbase
- 9、并发安全测试
- 二、优化点
- 参考资料
一、使用
1、参考资料
参考文档:
https://www.cnblogs.com/huan1993/p/16319931.html
https://blog.csdn.net/fu_huo_1993/article/details/124998602
https://gitee.com/huan1993/spring-cloud-parent/tree/master/drools/drools-dynamic-crud-rule
2、引包
gradle引包:
implementation 'org.drools:drools-core:7.74.1.Final'
implementation 'org.drools:drools-compiler:7.74.1.Final'
implementation 'org.drools:drools-templates:7.74.1.Final'
implementation 'org.drools:drools-mvel:7.74.1.Final'
implementation 'org.kie:kie-api:7.74.1.Final'
implementation ('org.kie:kie-spring:7.74.1.Final') {exclude(group: 'org.springframework', module: 'spring-tx')exclude(group: 'org.springframework', module: 'spring-beans')exclude(group: 'org.springframework', module: 'spring-core')exclude(group: 'org.springframework', module: 'spring-context')
}
maven引包:
可以参照大佬写的引(我没试过),或者按照我上面的引入。
<dependencyManagement><dependencies><dependency><groupId>org.drools</groupId><artifactId>drools-bom</artifactId><type>pom</type><version>7.69.0.Final</version><scope>import</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>2.6.7</version><scope>import</scope><type>pom</type></dependency></dependencies>
</dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.drools</groupId><artifactId>drools-compiler</artifactId></dependency><dependency><groupId>org.drools</groupId><artifactId>drools-mvel</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.22</version></dependency>
</dependencies>
3、创建规则实体类
此实体类和数据库中的表是一一对应的。
需要注意的属性:
kieBaseName: 创建的kbase的名字。
kiePackageName:该kbase的属性package的值。
import lombok.Getter;
import lombok.Setter;import java.util.Date;/*** drools 规则实体类** @author huan.fu* @date 2022/5/27 - 10:00*/
@Getter
@Setter
public class DroolsRule {/*** 规则id*/private Long ruleId;/*** kbase的名字*/private String kieBaseName;/*** 设置该kbase需要从那个目录下加载文件,这个是一个虚拟的目录,相对于 `src/main/resources`* 比如:kiePackageName=rules/rule01 那么当前规则文件写入路径为: kieFileSystem.write("src/main/resources/rules/rule01/1.drl")*/private String kiePackageName;/*** 规则内容*/private String ruleContent;/*** 规则创建时间*/private Date createdTime;/*** 规则更新时间*/private Date updateTime;public void validate() {if (this.ruleId == null || isBlank(kieBaseName) || isBlank(kiePackageName) || isBlank(ruleContent)) {throw new RuntimeException("参数有问题");}}private boolean isBlank(String str) {return str == null || str.isEmpty();}
}
4、实现drools动态规则
需要注意的是:
KieFileSystem 需要是单例的,即使用的是同一个。
KieContainer需要是单例的,即使用的是同一个。
通过updateToKieModule方法动态更新。
import com.huan.drools.entity.DroolsRule;
import lombok.extern.slf4j.Slf4j;
import org.drools.compiler.kie.builder.impl.InternalKieModule;
import org.drools.compiler.kie.builder.impl.KieContainerImpl;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.stereotype.Component;import java.util.Collection;
import java.util.List;/*** drools 管理*/
@Component
@Slf4j
public class DroolsManager {// 此类本身就是单例的private final KieServices kieServices = KieServices.get();// kie文件系统,需要缓存,如果每次添加规则都是重新new一个的话,则可能出现问题。即之前加到文件系统中的规则没有了private final KieFileSystem kieFileSystem = kieServices.newKieFileSystem();// 可以理解为构建 kmodule.xmlprivate final KieModuleModel kieModuleModel = kieServices.newKieModuleModel();// 需要全局唯一一个,如果每次加个规则都新创建一个,那么旧需要销毁之前创建的kieContainer,如果此时有正在使用的KieSession,则可能有问题private KieContainer kieContainer;/*** 判断该kbase是否存在*/public boolean existsKieBase(String kieBaseName) {if (null == kieContainer) {return false;}Collection<String> kieBaseNames = kieContainer.getKieBaseNames();if (kieBaseNames.contains(kieBaseName)) {return true;}log.info("需要创建KieBase:{}", kieBaseName);return false;}public void deleteDroolsRule(String kieBaseName, String packageName, String ruleName) {if (existsKieBase(kieBaseName)) {KieBase kieBase = kieContainer.getKieBase(kieBaseName);kieBase.removeRule(packageName, ruleName);log.info("删除kieBase:[{}]包:[{}]下的规则:[{}]", kieBaseName, packageName, ruleName);}}/*** 添加或更新 drools 规则*/public void addOrUpdateRule(DroolsRule droolsRule) {// 获取kbase的名称String kieBaseName = droolsRule.getKieBaseName();// 判断该kbase是否存在boolean existsKieBase = existsKieBase(kieBaseName);// 该对象对应kmodule.xml中的kbase标签KieBaseModel kieBaseModel = null;if (!existsKieBase) {// 创建一个kbasekieBaseModel = kieModuleModel.newKieBaseModel(kieBaseName);// 不是默认的kieBasekieBaseModel.setDefault(false);// 设置该KieBase需要加载的包路径kieBaseModel.addPackage(droolsRule.getKiePackageName());// 设置kieSessionkieBaseModel.newKieSessionModel(kieBaseName + "-session")// 不是默认session.setDefault(false);} else {// 获取到已经存在的kbase对象kieBaseModel = kieModuleModel.getKieBaseModels().get(kieBaseName);// 获取到packagesList<String> packages = kieBaseModel.getPackages();if (!packages.contains(droolsRule.getKiePackageName())) {kieBaseModel.addPackage(droolsRule.getKiePackageName());log.info("kieBase:{}添加一个新的包:{}", kieBaseName, droolsRule.getKiePackageName());} else {kieBaseModel = null;}}String file = "src/main/resources/" + droolsRule.getKiePackageName() + "/" + droolsRule.getRuleId() + ".drl";log.info("加载虚拟规则文件:{}", file);kieFileSystem.write(file, droolsRule.getRuleContent());if (kieBaseModel != null) {String kmoduleXml = kieModuleModel.toXML();log.info("加载kmodule.xml:[\n{}]", kmoduleXml);kieFileSystem.writeKModuleXML(kmoduleXml);}KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);// 通过KieBuilder构建KieModule下所有的KieBasekieBuilder.buildAll();// 获取构建过程中的结果Results results = kieBuilder.getResults();// 获取错误信息List<Message> messages = results.getMessages(Message.Level.ERROR);if (null != messages && !messages.isEmpty()) {for (Message message : messages) {log.error(message.getText());}throw new RuntimeException("加载规则出现异常");}// KieContainer只有第一次时才需要创建,之后就是使用这个if (null == kieContainer) {kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());} else {// 实现动态更新((KieContainerImpl) kieContainer).updateToKieModule((InternalKieModule) kieBuilder.getKieModule());}}/*** 触发规则,此处简单模拟,会向规则中插入一个Integer类型的值*/public String fireRule(String kieBaseName, Integer param) {// 创建kieSessionKieSession kieSession = kieContainer.newKieSession(kieBaseName + "-session");StringBuilder resultInfo = new StringBuilder();kieSession.setGlobal("resultInfo", resultInfo);kieSession.insert(param);kieSession.fireAllRules();kieSession.dispose();return resultInfo.toString();}
}
5、模拟数据库,实现规则的CRUD
此处是使用内存保存规则,也可以保存到数据库中。
import com.huan.drools.DroolsManager;
import com.huan.drools.entity.DroolsRule;
import com.huan.drools.service.DroolsRuleService;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import java.util.*;@Service
public class DroolsRuleServiceImpl implements DroolsRuleService {@Resourceprivate DroolsManager droolsManager;/*** 模拟数据库*/private Map<Long, DroolsRule> droolsRuleMap = new HashMap<>(16);@Overridepublic List<DroolsRule> findAll() {return new ArrayList<>(droolsRuleMap.values());}@Overridepublic void addDroolsRule(DroolsRule droolsRule) {droolsRule.validate();droolsRule.setCreatedTime(new Date());droolsRuleMap.put(droolsRule.getRuleId(), droolsRule);droolsManager.addOrUpdateRule(droolsRule);}@Overridepublic void updateDroolsRule(DroolsRule droolsRule) {droolsRule.validate();droolsRule.setUpdateTime(new Date());droolsRuleMap.put(droolsRule.getRuleId(), droolsRule);droolsManager.addOrUpdateRule(droolsRule);}@Overridepublic void deleteDroolsRule(Long ruleId, String ruleName) {DroolsRule droolsRule = droolsRuleMap.get(ruleId);if (null != droolsRule) {droolsRuleMap.remove(ruleId);droolsManager.deleteDroolsRule(droolsRule.getKieBaseName(), droolsRule.getKiePackageName(), ruleName);}}
}
6、创建控制层
@RestController
@RequestMapping("/drools/rule")
public class DroolsRuleController {@Resourceprivate DroolsRuleService droolsRuleService;@Resourceprivate DroolsManager droolsManager;@GetMapping("findAll")public List<DroolsRule> findAll() {return droolsRuleService.findAll();}@PostMapping("add")public String addRule(@RequestBody DroolsRule droolsRule) {droolsRuleService.addDroolsRule(droolsRule);return "添加成功";}@PostMapping("update")public String updateRule(@RequestBody DroolsRule droolsRule) {droolsRuleService.updateDroolsRule(droolsRule);return "修改成功";}@PostMapping("deleteRule")public String deleteRule(Long ruleId, String ruleName) {droolsRuleService.deleteDroolsRule(ruleId, ruleName);return "删除成功";}@GetMapping("fireRule")public String fireRule(String kieBaseName, Integer param) {return droolsManager.fireRule(kieBaseName, param);}
}
7、测试规则的动态添加
(1)添加规则
curl --location --request POST 'http://localhost:8080/drools/rule/add' \
--header 'User-Agent: apifox/1.0.0 (https://www.apifox.cn)' \
--header 'Content-Type: application/json' \
--data-raw '{"ruleId": 1,"kieBaseName": "kieBase01","kiePackageName": "rules.rule01","ruleContent": "package rules.rule01 \n global java.lang.StringBuilder resultInfo \n rule \"rule-01\" when $i: Integer() then resultInfo.append(drools.getRule().getPackageName()).append(\".\").append(drools.getRule().getName()).append(\"执行了,前端传递的参数:\").append($i); end"
}'
package rules.rule01global java.lang.StringBuilder resultInforule "rule-01"when$i: Integer()thenresultInfo.append(drools.getRule().getPackageName()).append(".").append(drools.getRule().getName()).append("执行了,前端传递的参数:").append($i);
end
运行:
➜ ~ curl http://localhost:8080/drools/rule/fireRule\?kieBaseName\=kieBase01\¶m\=1
rules.rule01.rule-01执行了,前端传递的参数:1%
➜ ~
可以看到我们动态加载的规则执行了。
(2)修改规则
需求: 在上面(1)测试规则的动态添加的基础上,修改规则。
之前的规则:
package rules.rule01global java.lang.StringBuilder resultInforule "rule-01"when$i: Integer()thenresultInfo.append(drools.getRule().getPackageName()).append(".").append(drools.getRule().getName()).append("执行了,前端传递的参数:").append($i);
end
修改后的规则:
package rules.rule01global java.lang.StringBuilder resultInforule "rule-01"when$i: Integer(intValue() > 3) // 注意此处修改了thenresultInfo.append(drools.getRule().getPackageName()).append(".").append(drools.getRule().getName()).append("执行了,前端传递的参数:").append($i);
end
可以看到修改的地方为$i: Integer(intValue() > 3)
,即增加了一个条件判断。
运行修改规则:
➜ ~ curl --location --request POST 'http://localhost:8080/drools/rule/update' \
--header 'User-Agent: apifox/1.0.0 (https://www.apifox.cn)' \
--header 'Content-Type: application/json' \
--data-raw '{"ruleId": 1,"kieBaseName": "kieBase01","kiePackageName": "rules.rule01","ruleContent": "package rules.rule01 \n global java.lang.StringBuilder resultInfo \n rule \"rule-01\" when $i: Integer(intValue() > 3) then resultInfo.append(drools.getRule().getPackageName()).append(\".\").append(drools.getRule().getName()).append(\"执行了,前端传递的参数:\").append($i); end"
}'
此处修改了规则内存中Integer的值必须>3
时才执行。
运行:
➜ ~ curl http://localhost:8080/drools/rule/fireRule\?kieBaseName\=kieBase01\¶m\=1
➜ ~ curl http://localhost:8080/drools/rule/fireRule\?kieBaseName\=kieBase01\¶m\=6
rules.rule01.rule-01执行了,前端传递的参数:6%
➜ ~
从上面可以看到,当我们传递的param=1时,没有结果数据,当param=6时有结果输出。
(3)删除规则
➜ ~ curl --location --request POST 'http://localhost:8080/drools/rule/deleteRule?ruleId=1&ruleName=rule-01'删除成功%
➜ ~
运行结果
➜ ~ curl http://localhost:8080/drools/rule/fireRule\?kieBaseName\=kieBase01\¶m\=6
➜ ~ curl http://localhost:8080/drools/rule/fireRule\?kieBaseName\=kieBase01\¶m\=1
➜ ~
可以看到删除成功了。
8、模拟2个kbase
1、添加规则并执行
➜ ~ curl --location --request POST 'http://localhost:8080/drools/rule/add' \
--header 'Content-Type: application/json' \
--data-raw '{"ruleId": 1,"kieBaseName": "kieBase01","kiePackageName": "rules.rule01","ruleContent": "package rules.rule01 \n global java.lang.StringBuilder resultInfo \n rule \"rule-01\" when $i: Integer() then resultInfo.append(drools.getRule().getPackageName()).append(\".\").append(drools.getRule().getName()).append(\"执行了,前端传递的参数:\").append($i); end"
}'
添加成功%
➜ ~ curl --location --request POST 'http://localhost:8080/drools/rule/add' \
--header 'Content-Type: application/json' \
--data-raw '{"ruleId": 2,"kieBaseName": "kieBase02","kiePackageName": "rules.rule02","ruleContent": "package rules.rule02 \n global java.lang.StringBuilder resultInfo \n rule \"rule-01\" when $i: Integer() then resultInfo.append(drools.getRule().getPackageName()).append(\".\").append(drools.getRule().getName()).append(\"执行了,前端传递的参数:\").append($i); end"
}'
添加成功%
➜ ~ curl http://localhost:8080/drools/rule/fireRule\?kieBaseName\=kieBase01\¶m\=1
rules.rule01.rule-01执行了,前端传递的参数:1%
➜ ~ curl http://localhost:8080/drools/rule/fireRule\?kieBaseName\=kieBase02\¶m\=1
rules.rule02.rule-01执行了,前端传递的参数:1%
➜ ~
2、执行
9、并发安全测试
经测试,并发修改规则+执行规则,并不会出现问题!
二、优化点
1、加一个DroolsManager加载时,从数据源中读取规则,然后依次添加。
2、实际用到的是KieSession,可以添加一个方法:
//根据kiebase 名字获取kiesession
public KieSession getKieSessionBySessionName(String kieBaseName) {KieSession kieSession = kieContainer.newKieSession(kieBaseName + "-session");return kieSession;
}
3、数据库部分没有完整实现,可以考虑实现多种数据源,其实mysql一种就够了。
参考资料
最新版本:8.44.2.FINAL
官方文档:
https://www.drools.org/learn/documentation.html
8版本:https://docs.drools.org/8.44.0.Final/drools-docs/drools/introduction/index.html
7版本:https://docs.drools.org/7.74.1.Final/drools-docs/html_single/index.html