欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Drools的Java入门Demo

程序员文章站 2022-05-22 11:22:09
...

1.pom.xml中添加Drools的依赖包:

        <dependency>
            <groupId>org.kie</groupId>
            <artifactId>kie-api</artifactId>
            <version>7.1.0.Final</version>
        </dependency>

参考:KIE是jBoss里面一些相关项目的统称,例如jBPM和Drools。这些项目都有一定的关联关系,并且存在一些通用的API,比如说涉及到构建(building)、部署(deploying)和加载(loading)等方面的,这些API就都会以KIE作为前缀来表示这些是通用的API。

Drools的Java入门Demo

2.创建HelloDrools:

package yzh;

import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;


public class HelloDrools {

    public static void main(String[] args) {
        KieServices kieServices = KieServices.Factory.get();
//        KieContainer kieContainer = kieServices.newKieClasspathContainer();
        KieContainer kieContainer = kieServices.getKieClasspathContainer();//kmodule.xml
        KieSession kieSession = kieContainer.newKieSession("helloWorldSession");
        //加入数据
        yzh.Message message = new yzh.Message();
        message.setId("123");
        message.setName("haha");
        kieSession.insert(message);
        //执行规则
        int i = kieSession.fireAllRules();//fire:火
        System.out.println("========"+i);
        kieSession.dispose();//处置,处理
    }

}

其中Message对象:

package yzh;


public class Message {

    String id;

    String name;

    public Message() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Message(String id, String name) {
        this.id = id;
        this.name = name;
    }
}

3.在resources目录下创建META-INF文件夹,新建kmodule.xml配置文件:

<?xml version="1.0" encoding="UTF-8" ?>
<kmodule xmlns="http://www.drools.org/xsd/kmodule">
    <kbase name="helloWorldBase">
        <ksession name="helloWorldSession"/>
    </kbase>
</kmodule>

4.在resources目录下新建规则的配置文件helloworldDrools.drl,文件名helloworldDrools随意起:


dialect  "mvel"

rule "helloworldDrools"
    when
        eval(true)
    then
        System.out.println("hi Drools I can see you");
end

rule "hello2"
    when
        m : yzh.Message(id=="123",name=="haha")
    then
      System.out.println("=========get fact and then rule operate fact========");
end

rule "hello3"
    when
        m : yzh.Message(id=="456",name=="haha")
//        s : String("haha")
    then
      System.out.println("=========get fact and then rule operate fact456========");
end

5.执行,可以看到执行结果:

hi Drools I can see you
=========get fact and then rule operate fact========
========2

 

相关标签: Drools