Drools 6从String加载并执行规则

时间:2015-12-22 15:09:40

标签: drools

我正在尝试从Drools 6中的String加载规则,如下所示:

// the rule
def drl = '''
dialect "mvel"

rule "Person is over 18"
    when
        $person : Person(age > 18)
    then
        System.out.println("Person is "+$person.name);
end
'''
// setup for rule
KieServices kieServices = KieServices.Factory.get()
KieFileSystem kfs = kieServices.newKieFileSystem()
kfs.write( "src/main/resources/simple.drl",
    kieServices.getResources().newReaderResource( new StringReader(drl) ) )
KieBuilder kieBuilder = kieServices.newKieBuilder( kfs ).buildAll()

// check there have been no errors for rule setup
Results results = kieBuilder.getResults();
if( results.hasMessages( Message.Level.ERROR ) ){
    println( results.getMessages() )
    throw new IllegalStateException( "### errors ###" )
}
KieContainer kieContainer =
    kieServices.newKieContainer( kieBuilder.getKieModule().getReleaseId() )
KieSession kieSession = kieContainer.newKieSession()

// insert facts and fire rules
kieSession.insert(new Person("Jon Doe", 21))
kieSession.insert(new Person("Jon Darcy", 1))
kieSession.fireAllRules()

kieSession.dispose()

@Immutable
class Person {
    String name
    int age
}

我想要发生的是打印出人名。通过附加eventlistener和logger,我可以看到事实被添加和断言。通过在drl中出错,我可以确定看到和编译规则。但规则永远不会发生。

我很确定代码中某处有一个愚蠢的小错误。有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:5)

从KieContainer获取KieBase并从中创建KieSession对我有用:

String drl = "package drlstring;\n" +
    "dialect 'mvel'\n" +
    "rule Person_is_over_18\n" +
    "when\n" +
    "$person : Person(age > 18)\n" +
    "then\n" +
    "System.out.println(\"Person is \"+$person.getName());\n" +
    "end";
// setup for rule
KieServices kieServices = KieServices.Factory.get();
KieFileSystem kfs = kieServices.newKieFileSystem();
kfs.write( "src/main/resources/simple.drl",
       kieServices.getResources().newReaderResource( new StringReader(drl) ) );
KieBuilder kieBuilder = kieServices.newKieBuilder( kfs ).buildAll();

// check there have been no errors for rule setup
Results results = kieBuilder.getResults();
if( results.hasMessages( Message.Level.ERROR ) ){
    System.out.println( results.getMessages() );
    throw new IllegalStateException( "### errors ###" );
}
KieContainer kieContainer =
    kieServices.newKieContainer( kieBuilder.getKieModule().getReleaseId() );
KieSession kieSession = kieContainer.newKieSession();

// insert facts and fire rules
kieSession.insert(new Person("Jon Doe", 21));
kieSession.insert(new Person("Jon Darcy", 1));
kieSession.fireAllRules();
kieSession.dispose();

但是你的代码也在运行 - 至少在用Java完成所有代码之后,并确保Person和DRL文件在同一个包中。

rule hello
when then 
  System.out.println( "Hello!" );
end

如果您想继续使用Scala设置,请通过添加空条件规则来缩小触发失败的可能原因:

itertools

认为是Drools引擎无法识别的类Person的Scala定义。