规则引擎Drools简单使用
Drools依赖引入
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-api</artifactId>
<version>6.5.0.Final</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-compiler</artifactId>
<version>6.5.0.Final</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-core</artifactId>
<version>6.5.0.Final</version>
</dependency>
新增xml配置文件
kbase定义
name:kbase名称
packages:规则文件所在包路径,多个使用逗号分隔
ksession定义
name:ksession名称
<?xml version="1.0" encoding="UTF-8"?>
<kmodule xmlns="http://jboss.org/kie/6.0.0/kmodule">
<kbase name="documentMatchRule" packages="rules">
<ksession name="documentMatchSession"/>
</kbase>
</kmodule>
新增drl文件
package:标识每个drl文件,无实际含义
DeliverDocumentRule:规则文件
package rules
import xxx.DeliverDocumentRule
import org.apache.commons.lang.StringUtils
rule "rule_catalogueMatch"
when
$deliverDocumentRule : DeliverDocumentRule(!StringUtils.isEmpty(filePathRule) && filePath contains filePathRule)
then
System.out.println("文件路径【" + $deliverDocumentRule.getFilePath() + "】匹配规则【"
+ $deliverDocumentRule.getFilePathRule() + "】成功");
end
获取KieContainer
private KieContainer getKieContainer() {
KieServices ks = KieServices.Factory.get();
return ks.getKieClasspathContainer(this.getClass().getClassLoader());
}
获取KieSession
private KieSession getKieSession(KieContainer kContainer) {
return kContainer.newKieSession(DOCUMENT_MATCH_SESSION);
}
规则匹配
documentRule:匹配规则
ruleName:匹配的规则名称
matchNum:匹配的成功的数量
// 插入
kSession.insert(documentRule);
// 执行规则
int matchNum = kSession.fireAllRules(new RuleNameStartsWithAgendaFilter(ruleName));