功能背景
在使用drools规则文件都是在src/main/resources目录下写死规则文件的,这样不够灵活。想在程序运行的过程中动态去修改规则。
代码实例
定义规则实体类
public class RuleContent {
/**
* 名称
*/
private String projectName;
/**
* 会话编码
*/
private String sessionCode;
/**
* 规则内容
*/
private String ruleContent;
/**
* 生效状态
*/
private Boolean valid;
}
规则动态更新
public class RuleConfigManage {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final KieServices kieServices = KieServices.Factory.get();
private final KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
private final KieModuleModel kieModuleModel = kieServices.newKieModuleModel();
private KieContainer kieContainer;
private KieContainerSessionsPool sessionsPool;
public void updateSomeRule(List<RuleContent> ruleContentList) {
if (CollectionUtils.isEmpty(ruleContentList)) {
return;
}
Collection<String> kieBaseNames = Objects.nonNull(kieContainer) ? kieContainer.getKieBaseNames() : new ArrayList<>();
for (RuleContent ruleContent : ruleContentList) {
String sessionCode = ruleContent.getSessionCode();
if (kieBaseNames.contains(sessionCode) && !ruleContent.getValid()) {
KieBase kieBase = kieContainer.getKieBase(sessionCode);
kieBase.removeKiePackage(sessionCode);
logger.info("removeRule:{}", sessionCode);
continue;
}
if (!ruleContent.getValid()) {
continue;
}
KieBaseModel kieBaseModel = kieModuleModel.newKieBaseModel(sessionCode).addPackage(sessionCode);
kieBaseModel.newKieSessionModel(sessionCode).setType(KieSessionModel.KieSessionType.STATEFUL);
String path = String.format("src/main/resources/%s/rule.drl", sessionCode);
String drl = ruleContent.getRuleContent();
kieFileSystem.write(path, drl);
String kModuleXML = kieModuleModel.toXML();
logger.info("updateSomeRule:\n{}", kModuleXML);
kieFileSystem.writeKModuleXML(kModuleXML);
KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem).buildAll();
Results results = kieBuilder.getResults();
if (results.hasMessages(Message.Level.ERROR)) {
List<Message> messages = results.getMessages(Message.Level.ERROR);
messages.forEach(msg -> logger.error(msg.getText()));
}
if (Objects.nonNull(kieContainer)) {
((KieContainerImpl) kieContainer).updateToKieModule((InternalKieModule) kieBuilder.getKieModule());
} else {
kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());
sessionsPool = kieContainer.newKieSessionsPool(Constant.KIE_SESSIONS_POOL);
}
}
}
}