如何在启动时从数据库表加载规则并在Drools 6.2.0中从同一个表中更新它们?我找到了一个example使用Drools 5,我可以将其从Scala转换为Java,但看起来API已经发生了很大变化......例如,我没有看到RuleBaseFactory类。
任何样本或文档都将受到赞赏。
答案 0 :(得分:8)
我不确定org.drools.RuleBaseFactory
的拍摄地点。以下是在Drools 5.3(以及可能更早)中完成的工作方式,最高可达5.6:
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add( ..., ResourceType.DRL);
if( kbuilder.hasErrors() ){
System.err.println( "### compilation errors ###" );
KnowledgeBuilderErrors errors = kbuilder.getErrors();
for( KnowledgeBuilderError err: errors ){
System.err.println( err.toString() );
}
throw new IllegalStateException( "compile errors" );
}
KnowledgeBase kbase = kbuilder.newKnowledgeBase();
StatelessKnowledgeSession ksession = kbase.newStatelessKnowledgeSession();
省略号表示插入包含规则文本的数据的位置。检查API是否有合适的类型; java.lang.String
应该可以接受。
这是我用于6.2的方式:
KieServices kieServices = KieServices.Factory.get();
KieFileSystem kfs = kieServices.newKieFileSystem();
kfs.write( "src/main/resources/simple.drl", ... );
KieBuilder kieBuilder = kieServices.newKieBuilder( kfs ).buildAll();
Results results = kieBuilder.getResults();
if( results.hasMessages( Message.Level.ERROR ) ){
System.out.println( results.getMessages() );
throw new IllegalStateException( "### errors ###" );
}
KieContainer kieContainer =
kieServices.newKieContainer( kieServices.getRepository().getDefaultReleaseId() );
KieBase kieBase = kieContainer.getKieBase();
kieSession = kieContainer.newKieSession();
答案 1 :(得分:4)
drools-templates有ResultSetGenerator.java,它有方法compile(resultSet,template)来完成这项工作。
我有数据通过HTTP转换为规则。我找到了一种使用ObjectDataCompiler执行此操作的方法。可能有些人可能觉得这很有用。
ObjectDataCompiler compiler = new ObjectDataCompiler();
String generatedDRL = compiler.compile(ruleAttributes, new FileInputStream(REGULATION_TEMPLATE_FILE));
其中ruleAttributes是
List<Map<String, String>> ruleAttributes = new ArrayList<>();
Map<String, String> rule1 = new HashMap<>();
rule1.put("ruleid", "2");
rule1.put("ifcondition", "abc: Abc(xyz.getId() == 2);");
rule1.put("thencondition", "myGlobal.setPqr(200.1D);");
ruleAttributes.add(rule1);
然后可以像这样创建KieBase:
KieServices kieServices = KieServices.Factory.get();
KieHelper kieHelper = new KieHelper();
//multiple such resoures/rules can be added
byte[] b1 = generatedDRL.getBytes();
Resource resource1 = kieServices.getResources().newByteArrayResource(b1);
kieHelper.addResource(resource1, ResourceType.DRL);
KieBase kieBase = kieHelper.build();
规则可以这样应用:
KieSession kieSession = kieBase.newKieSession();
kieSession.setGlobal("myGlobal", myGlobal);
kieSession.insert(abc);
int numberOfRulesFired = kieSession.fireAllRules();
kieSession.dispose();
模板文件如下所示:
template header
ruleid
ifcondition
thencondition
import fk.sp.seldon.msku.MSKU
global com.something.blah.MyGlobal myGlobal
template "tmp1"
rule "@{ruleid}"
dialect "mvel"
when
@{ifcondition}
then
@{thencondition};
end
end template