Drools 7.X 动态加载规则
程序员文章站
2022-03-03 15:55:36
...
动态加载规则:就是不直接写drl规则文件,从数据库中读取数据,然后拼接成字符串,再加载到work memory中。下面是执行代码:
动态拼接字符串:
public String rule2Drl(Rule rule) {
StringBuilder result = new StringBuilder();
/*package部分*/
result.append("package rule1;\r\n");
result.append("\r\n");
/*导包部分*/
result.append("import com.winning.rules.engine.model.Fact;\r\n");
result.append("import com.winning.rules.engine.model.FactProperty;\r\n");
result.append("import java.util.List;\r\n");
result.append("\r\n");
/*规则申明部分*/
result.append("rule \"32353242\"\r\n");
/*规则属性部分*/
/*规则条件部分*/
result.append("\twhen\r\n");
result.append("\t\teval(true)\r\n");
/*规则结果部分*/
result.append("\tthen\r\n");
result.append("\t\tSystem.out.println(\"动态加载的规则被触发了\");\r\n");
/*规则结束*/
result.append("end\r\n");
return result.toString();
}
代码上面没有写具体的业务逻辑,可根据需要自动添加。
拼接好字符串以后,就需要去build了,首先使用的方法是KnowledgeBase,也就是知识库加载,方法可以执行成功,但是KnowledgeBase这个类过时了。
方法一:
public void handle() {
StatefulKnowledgeSession kSession = null;
try {
RuleHandle ruleHandle = new RuleHandle();
KieHelper helper = new KieHelper();
helper.addContent(ruleHandle.rule2Drl(null), ResourceType.DRL);
KnowledgeBuilder kb = KnowledgeBuilderFactory.newKnowledgeBuilder();
//装入规则,可以装入多个
kb.add(ResourceFactory.newByteArrayResource(ruleHandle.rule2Drl(null).getBytes("utf-8")), ResourceType.DRL);
KnowledgeBuilderErrors errors = kb.getErrors();
for (KnowledgeBuilderError error : errors) {
System.out.println(error);
}
KnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
kBase.addKnowledgePackages(kb.getKnowledgePackages());
kSession = kBase.newStatefulKnowledgeSession();
kSession.insert(new Object());
kSession.fireAllRules();
kSession.dispose();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
方法二:看了文档以后发现最新的动态加载KieHelper 这个类来实现的,具体代码如下:
public void handle() {
RuleHandle ruleHandle = new RuleHandle();
KieHelper helper = new KieHelper();
helper.addContent(ruleHandle.rule2Drl(null), ResourceType.DRL);
KieSession kSession = helper.build().newKieSession();
kSession.insert(new Object());
kSession.fireAllRules();
kSession.dispose();
}
这样很简单就可以加载出来规则了