Drools学习三:新建项目
Step 1.
新建一个Drools项目
选择第一个,新建一个空项目,点击Next,输入项目名,点击Finish完成创建
此时会自动生成一些目录结构
src.main.java.com.sample中存放java程序
src.main.resources.com.sample中存放drools文件,分别为dtables决策表、process规则流、rules规则
Step 2.
添加JUnit单元测试框架,用来完成后面的项目运行工作
项目名称上单击鼠标右键,选择Build Path→Configure Build Path
选择Java Build Path→Libraries→Add Library→JUnit→Next,选择JUnit版本点击Finish,应用并关闭设置窗口
Step 3.
在com.sample目录下创建util文件夹,用来存放工具类
创建类KnowledgeSessionHelper用来生成drools服务
package com.sample.util;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.StatelessKieSession;
public class KnowledgeSessionHelper {
public static KieContainer createRuleBase() {
KieServices ks = KieServices.Factory.get();
KieContainer kieContainer = ks.getKieClasspathContainer();
return kieContainer;
}
public static StatelessKieSession getStatelessKnowledgeSession(KieContainer kieContainer, String sessionName) {
StatelessKieSession kSession = kieContainer.newStatelessKieSession(sessionName);
return kSession;
}
public static KieSession getStatefulKnowledgeSession(KieContainer kieContainer, String SessionName) {
KieSession kSession = kieContainer.newKieSession(SessionName);
return kSession;
}
}
Step 4.
编写测试类并运行
package com.sample;
import org.junit.jupiter.api.Test;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import com.sample.util.KnowledgeSessionHelper;
class FirstTry {
KieSession sessionStatefull = null;
static KieContainer kieContainer;
@Test
void test() {
kieContainer = KnowledgeSessionHelper.createRuleBase();
sessionStatefull = KnowledgeSessionHelper.getStatefulKnowledgeSession(kieContainer, "ksession-rules");
sessionStatefull.fireAllRules();
}
}
观察JUnit窗口是否运行成功,当然此时并没有规则被执行
Step 5.
创建规则
在src/main/java/com/sample下创建新目录lesson1,用于存放规则
修改src/main/resources/META-INF目录下kmodule.xml文件,指向新的规则存放目录
<?xml version="1.0" encoding="UTF-8"?>
<kmodule xmlns="http://jboss.org/kie/6.0.0/kmodule">
<kbase name="rules" packages="com.sample.rules">
<ksession name="ksession-rules"/>
</kbase>
<kbase name="dtables" packages="com.sample.dtables">
<ksession name="ksession-dtables"/>
</kbase>
<kbase name="process" packages="com.sample.process">
<ksession name="ksession-process"/>
</kbase>
<kbase name="rules_lesson1" packages="com.sample.rules">
<ksession name="ksession-rules-lesson1"/>
</kbase>
</kmodule>
在新建的目录下新建规则文件lesson1.drl
修改lesson1.drl文件
//created on: 2020-2-14
package com.sample.lesson1
//list any import classes here.
//declare any global variables here
rule "Your First Rule"
when
//conditions
then
//actions
System.out.println("Hello Drools");
end
rule "Your Second Rule"
//include attributes such as "salience" here...
when
//conditions
then
//actions
end
再次执行FirstTry测试类,此时输出为
规则创建成功
上一篇: Java的抽象类
下一篇: Rails 1.2.6发布!
推荐阅读