我有一个用例,我需要为一次性使用动态创建规则。规则是动态的,在更糟糕的情况下,每个迭代/请求可能会有所不同。因此,我无法存储它们。
我目前对 Drools 的理解是,你需要创建一个 KnowledgeBuilder,然后添加规则。
我正在创建知识库,如下所示。
private KnowledgeBase readKnowledgeBase() throws Exception {
long t1 = System.currentTimeMillis();
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
long t11 = System.currentTimeMillis();
kbuilder.add( org.drools.io.ResourceFactory.newByteArrayResource(getRule()), ResourceType.DRL);
long t2 = System.currentTimeMillis();
KnowledgeBuilderErrors errors = kbuilder.getErrors();
if (errors.size() > 0) {
for (KnowledgeBuilderError error: errors) {
System.err.println(error);
}
throw new IllegalArgumentException("Could not parse knowledge.");
}
long t3 = System.currentTimeMillis();
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
long t4 = System.currentTimeMillis();
kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
long t5 = System.currentTimeMillis();
Collection<KnowledgePackage> kpackages = kbase.getKnowledgePackages();
for (KnowledgePackage knowledgePackage : kpackages) {
System.out.println("Package -------- " + knowledgePackage.getName());
Collection<Rule> rules = knowledgePackage.getRules();
for (Rule rule : rules) {
System.out.println("****" + rule.getName());
}
}
long t6 = System.currentTimeMillis();
System.out.println( (t11-t1) + " " + (t2-t11) + " " + ( t3-t2) + " " + ( t4-t3) + " " + ( t5-t4) + " " + ( t6-t5)+ " " );
return kbase;
}
根据时序日志,代码仅在这两个操作中占用大部分时间(超过 80%)。有没有办法让它更快?或者有没有办法实现我的用例?
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add( org.drools.io.ResourceFactory.newByteArrayResource(getRule()), ResourceType.DRL);