Drools和Maven Hello World示例

x33g5p2x  于2022-10-15 转载在 Maven  
字(11.1k)|赞(0)|评价(0)|浏览(764)

在本教程中,我们将学习如何使用Maven作为项目生成器和最新版本的kie-Drools原型更新至2022年10月)创建一个基本的Drools规则引擎示例项目。
硬性要求:

*JDK8或更高版本
*Maven3.x

我们首先将学习如何从shell创建项目。作为替代方案,您可以使用类似Eclipse的IDE和Drools插件或Red Hat Code Ready Studio。

为Drools创建新的Maven项目

为了开始,您只需要一个基本的Maven原型,您可以使用它为我们的项目设置初始结构。我们将使用的原型是kie drools原型。我们将运行它的最新版本。
从shell发出以下命令:

mvn archetype:generate -B -DarchetypeGroupId=org.kie -DarchetypeArtifactId=kie-drools-archetype -DarchetypeVersion= -DgroupId=com.sample -DartifactId=helloworld -Dversion=1.0-SNAPSHOT -Dpackage=com.sample

原型将创建一个基本的Drool项目,其中包含一个示例Rule文件和一个Java类来测试它。
让我们看看这个项目的pom.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.sample</groupId>
  <artifactId>helloworld</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>kjar</packaging>

  <name>helloworld</name>
  <url>http://drools.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <drools-version>7.73.0.Final</drools-version>
    <slf4j-version>1.7.30</slf4j-version>
    <junit-version>4.13.1</junit-version>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.drools</groupId>
        <artifactId>drools-bom</artifactId>
        <type>pom</type>
        <version>${drools-version}</version>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>

    <dependency>
        <groupId>org.drools</groupId>
        <artifactId>drools-compiler</artifactId>
        <scope>test</scope>
      </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit-version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j-version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.kie</groupId>
        <artifactId>kie-maven-plugin</artifactId>
        <version>${drools-version}</version>
        <extensions>true</extensions>
      </plugin>
    </plugins>

  </build>
</project>

如您所见,我们的项目运行最新的Drools Engine 7.73.0.Final版本。如果您想尝试Kie Server的Beta版本,只需更新Drools version属性即可。

添加类和规则

好的,现在我们需要建立一个基于Server类的简单规则。如果Server类不满足最低要求,此规则将发出警告。

package com.sample;

public class Server {

    private String name;
    private int processors;
    private int memory;
    private int diskspace;
    private boolean isValid=true;

    public Server(String name, int processors, int memory, int diskspace) {
        this.name = name;
        this.processors = processors;
        this.memory = memory;
        this.diskspace = diskspace;
    }

    // Getter/Setters method omitted for brevity
}

接下来,在src/main/resources/rules.drl中添加一个简单的Rule文件:

import com.sample.Server
rule "Check Server Configuration"
  when
  $server : Server( processors < 2 || memory<=1024 || diskspace <= 2048)
  then
  $server.setValid(false);
  System.out.println("Server "+ $server.getName() + " configuration does not meet requirements!");
end

在文件夹srm/main/resources/META-INF下,您可以找到文件kmodule.xml,它为KIE项目提供声明性配置:

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

一个空的kmodule.xml文件意味着我们将使用默认KSession来插入事实并触发规则。
最后,让我们编写一个简单的Test类,它创建两个服务器对象,然后使用我们的规则验证它们:

package com.sample;

import org.junit.Test;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.definition.KiePackage;
import org.kie.api.definition.rule.Rule;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.junit.Assert.assertTrue;

public class RuleTest {
    static final Logger LOG = LoggerFactory.getLogger(RuleTest.class);

    @Test
    public void test() {
        KieServices kieServices = KieServices.Factory.get();

        KieContainer kContainer = kieServices.getKieClasspathContainer();

        LOG.info("Creating kieBase");
        KieBase kieBase = kContainer.getKieBase();

        LOG.info("There should be rules: ");
        for ( KiePackage kp : kieBase.getKiePackages() ) {
            for (Rule rule : kp.getRules()) {
                LOG.info("kp " + kp + " rule " + rule.getName());
            }
        }

        LOG.info("Creating kieSession");
        KieSession session = kieBase.newKieSession();

        LOG.info("Now running data");

        Server s1 = new Server("rhel7",2,1024,2048);
        session.insert(s1);
        session.fireAllRules();
        assertTrue(s1.isValid());

        Server s2 = new Server("rhel8",2,2048,4096);
        session.insert(s2);
        session.fireAllRules();
        assertTrue(s2.isValid());

    }
}

您可以按如下方式运行测试:

$ mvn clean install

预期结果是,第一个服务器配置将无法满足最低要求:

Server rhel7 configuration does not meet requirements!

您可以尝试增加第一台服务器的服务器值,并验证所有服务器配置现在都有效。
Drools Hello World示例的源代码位于:https://github.com/fmarchioni/mastertheboss/tree/master/drools/helloworld

使用CDI运行Hello World Drools

值得一提的是,CDI现在已紧密集成到KIE API中。您可以使用它在代码中注入KieSessionKieBases对象。下面是如何使用CDI重写上述示例。
首先,我们需要启用CDI,因此我们将在resources/META-INF文件夹下添加beans.xml文件

$ touch src/main/resources/META-INF/beans.xml

然后,让我们添加一个CDI Bean,它将被注入默认的KSession

package com.sample;

import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import org.kie.api.cdi.KSession;
import org.kie.api.runtime.KieSession;

import javax.inject.Inject;

public class CDIExample {

    @Inject
    @KSession
    KieSession session;

    public boolean go(Server server) {
        session.insert(server);
        session.fireAllRules();
        return server.isValid();
    }

    public static void main(String[] args) {

        Weld w = new Weld();
        WeldContainer wc = w.initialize();

        CDIExample bean = wc.instance().select(CDIExample.class).get();

        Server s1 = new Server("rhel7",2,2048,1024);

        boolean isValid = bean.go(s1);
        System.out.println("Configuration isValid "+isValid);
        w.shutdown();
    }

}

正如您所看到的,这个CDIBean还包含一个main方法,因此也可以使用maven-exec插件测试示例。
最后,让我们对创建Weld容器并Assert服务器有效性的Test类进行编码:

package com.sample;

import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import org.junit.Test;

import static org.junit.Assert.assertTrue;

public class RuleTest {

    @Test
    public void testGo() {

        Weld w = new Weld();
        WeldContainer wc = w.initialize();

        com.sample.CDIExample bean = wc.instance().select(com.sample.CDIExample.class).get();
        
        Server s1 = new Server("rhel7",2,2048,4096);

        boolean isValid = bean.go(s1);
        assertTrue(isValid);

        w.shutdown();

    }
}

在依赖项方面,您还必须包括cdiweld依赖项(不包括javax.el和javax.interceptor),以便能够使用cdi容器:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.drools</groupId>
    <artifactId>drools</artifactId>
    <version></version>
  </parent>
  <groupId>com.sample</groupId>
  <artifactId>helloworld-cdi</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>kjar</packaging>

  <name>helloworld-cdi</name>
  <url>http://drools.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <drools-version></drools-version>
    <slf4j-version>1.7.26</slf4j-version>
    <junit-version>4.12</junit-version>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.drools</groupId>
        <artifactId>drools-bom</artifactId>
        <type>pom</type>
        <version>${drools-version}</version>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>

 <dependency>
      <groupId>org.drools</groupId>
      <artifactId>drools-cdi</artifactId>
    </dependency>
    <dependency>
      <groupId>javax.enterprise</groupId>
      <artifactId>cdi-api</artifactId>
      <exclusions>
        <exclusion>
          <groupId>javax.el</groupId>
          <artifactId>javax.el-api</artifactId>
        </exclusion>
        <exclusion>
          <groupId>javax.interceptor</groupId>
          <artifactId>javax.interceptor-api</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>org.jboss.weld.se</groupId>
      <artifactId>weld-se-core</artifactId>
    </dependency>

    <dependency>
        <groupId>org.drools</groupId>
        <artifactId>drools-compiler</artifactId>
        <scope>test</scope>
      </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>

  </dependencies>

  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.kie</groupId>
        <artifactId>kie-maven-plugin</artifactId>
        <version>${drools-version}</version>
        <extensions>true</extensions>
      </plugin>
    </plugins>

  </build>
</project>

对于我们正在测试的单个服务器,单元测试将通过:

[INFO] Running com.sample.RuleTest
Aug 14, 2020 3:37:00 PM org.jboss.weld.bootstrap.WeldStartup <clinit>
INFO: WELD-000900: 2.4.1 (Final)
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Aug 14, 2020 3:37:07 PM org.jboss.weld.bootstrap.WeldStartup startContainer
INFO: WELD-000101: Transactional services not available. Injection of @Inject UserTransaction not available. Transactional observers will be invoked synchronously.
Aug 14, 2020 3:37:07 PM org.jboss.weld.environment.se.WeldContainer complete
INFO: WELD-ENV-002003: Weld SE container 6efac82c-0c7d-4297-91d2-c48811e91808 initialized
Aug 14, 2020 3:37:08 PM org.jboss.weld.environment.se.WeldContainer shutdown
INFO: WELD-ENV-002001: Weld SE container 6efac82c-0c7d-4297-91d2-c48811e91808 shut down
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 7.391 s - in com.sample.RuleTest

该项目在github https://github.com/fmarchioni/mastertheboss/tree/master/drools/helloworld-cdi上提供

通过以下教程继续学习Drools

1)决策表中的编码规则

在Drools中,决策表是一种根据输入电子表格的数据生成规则的方法。电子表格可以是标准Excel(XLS)或CSV文件。

2)Kie Execution Server入门

Kie Server是一个Java web应用程序,它允许我们公开使用REST和JMS接口远程执行的规则和业务流程。以下教程显示了如何在WildFly上安装它:在WildFly上配置Kie Execution Server

3)在Business Central上部署资产

熟悉Kie Execution Server之后,您就可以了解如何安装Business Central,以便在其中设计、构建和部署资产。

相关文章

最新文章

更多