添加drools框架运行的依赖
<!--Drools 规则相关 --> <dependency> <groupId>org.drools</groupId> <artifactId>drools-core</artifactId> <version>6.5.0.Final</version> </dependency> <dependency> <groupId>org.kie</groupId> <artifactId>kie-api</artifactId> <version>6.5.0.Final</version> </dependency> <dependency> <groupId>org.drools</groupId> <artifactId>drools-compiler</artifactId> <version>6.5.0.Final</version> </dependency>
public class DroolsHelloWorld { public static void main(String[] args) { // Class.forName( "org.drools.compiler.kie.builder.impl.KieServicesImpl" ).newInstance() KieServices kieServices = KieServices.Factory.get(); //会去 resource/META-INF 下找 kmodule.xml 文件 KieContainer kieContainer = kieServices.getKieClasspathContainer(); // kmodule.xml中<ksession name="helloworld"/> name值 KieSession kieSession = kieContainer.newKieSession("helloworld"); //启用规则 Set set=new HashSet(); set.add("helloworld1"); set.add("helloworld2"); int a = kieSession.fireAllRules(); /*FactHandle factHandle2 = kieSession.insert("456"); int b = kieSession.fireAllRules(new RuleNameEndsWithAgendaFilter("helloWorld1")); kieSession.delete(factHandle2);*/ kieSession.dispose(); } }
META-INF/kmodule.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<kmodule xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.drools.org/xsd/kmodule">
<!-- packages 指向规则文件目录 -->
<kbase name="hello" packages="com.dinpay.drools.helloworld">
<!-- name在 创建 KIEsession 会用到 -->
<ksession name="helloworld"/>
</kbase>
<!-- packages 指向规则文件目录 -->
<kbase name="helloUpgraded" packages="com.dinpay.drools.helloworldUpgraded">
<ksession name="helloworldUpgraded"/>
</kbase>
<!-- packages 指向规则文件目录 -->
<kbase name="dinpay" packages="rule2">
<ksession name="dinpayRule"/>
</kbase>
</kmodule>
droolsHelloWorld.drl脚本编写
rule helloWorld2 salience 100 lock-on-active true when eval(true) then System.out.println("Helloworld drools2! "); end rule helloWorld1 salience 100 lock-on-active true when eval(true) then System.out.println("Helloworld drools1! "); end