Drools - 更快地创建KnowlegeBuilder?

时间:2012-05-09 12:03:20

标签: performance dynamic rules drools

我有一个用例,我需要动态创建一个规则,仅供一次使用。规则是动态的,在更糟糕的情况下,每个迭代/请求可以是不同的。因此,我无法存储它们。

我目前对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); 

1 个答案:

答案 0 :(得分:0)

以下调用实际上将编译您的代码,即它调用JDT java编译器:

kbuilder.add(org.drools.io.ResourceFactory.newByteArrayResource(getRule()),ResourceType.DRL);

除非您使用内部API,否则无法避免这种情况,实际上使用起来非常复杂。

有一个中间步骤是使用描述符构建器API生成规范模型。它会为你节省几个周期,但最重要的操作是java编译。使用Descr Builder API的示例:

https://github.com/droolsjbpm/drools/blob/master/drools-compiler/src/test/java/org/drools/lang/api/DescrBuilderTest.java