drools规则引擎——helloworld
drools规则引擎是基于rete算法的实现。
drools 按照我的想法是根据配置文件来写复杂逻辑的判断条件,方便改
应用场景:
应用于问题确定的场合;
适用于非流程性规则匹配;
规则引擎简易语法参考:http://blog.csdn.net/quzishen/article/details/6163012
先来实例配置,按照网上教程实现clock时钟:
clock.java #pojo文件
package com; /** * Created by fdd on 2017/4/10. */ public class Clock { private int hour; private int minute; private int second; public int getHour() { return hour; } public void setHour(int hour) { this.hour = hour; } public int getMinute() { return minute; } public void setMinute(int minute) { this.minute = minute; } public int getSecond() { return second; } public void setSecond(int second) { this.second = second; } @Override public String toString() { return hour + ":" + minute + ":" + second; } }
clockTest.java 实例测试文件
package com; /** * Created by fdd on 2017/4/10. */ import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; public class ClockTest { public static void main(String[] args) { KieServices ks = KieServices.Factory.get(); KieContainer kContainer = ks.getKieClasspathContainer(); KieSession kSession = kContainer.newKieSession("session-clock"); kSession.insert(new Clock()); kSession.fireAllRules(); kSession.dispose(); } }
配置文件clock.drl
package com.ibm.clock
import com.Clock
rule "run"
salience 1
when
c: Clock(!(minute == 1 && second == 1))
then
System.out.println(c);
Thread.sleep(1000);
c.setSecond(c.getSecond() + 1);
update(c);
end
rule "second"
salience 2
when
c: Clock(second == 2);
then
c.setMinute(c.getMinute() + 1);
c.setSecond(0);
update(c);
end
rule "minute"
salience 3
when
c: Clock(minute == 60)
then
c.setHour(c.getHour() + 1);
c.setMinute(0);
update(c);
end
默认的kmodule.xml API默认读取路径为META-INF/kmodule.xml
<?xml version="1.0" encoding="UTF-8"?> <kmodule xmlns="http://jboss.org/kie/6.0.0/kmodule"> <kbase name="clock" packages="clock"> <ksession name="session-clock"/> </kbase> </kmodule>
maven配置文件
<dependencies> <!-- https://mvnrepository.com/artifact/org.kie/kie-api --> <dependency> <groupId>org.kie</groupId> <artifactId>kie-api</artifactId> <version>6.0.0.CR1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.drools/drools-compiler --> <dependency> <groupId>org.drools</groupId> <artifactId>drools-compiler</artifactId> <version>6.0.0.CR1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.drools/drools-core --> <dependency> <groupId>org.drools</groupId> <artifactId>drools-core</artifactId> <version>6.0.0.CR1</version> </dependency> </dependencies>