Drools 是用 Java 语言编写的开放源码规则引擎,使用 Rete 算法(参阅 参考资料)对所编写的规则求值。Drools 允许使用声明方式表达业务逻辑。可以使用非 XML 的本地语言编写规则,从而便于学习和理解。并且,还可以将 Java 代码直接嵌入到规则文件中,这令 Drools 的学习更加吸引人
Hello World
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-ci</artifactId>
<version>7.17.0.Final</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
Application
@SpringBootApplication
public class DroolsApplication {
public static void main(String[] args) {
SpringApplication.run(DroolsApplication.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
System.out.println("start to run task");
KieServices kieServices = KieServices.Factory.get();
KieContainer kieContainer = kieServices.newKieClasspathContainer();
KieSession kieSession = kieContainer.newKieSession("hello-rules");
kieSession.fireAllRules();
kieSession.destroy();
};
}
}
-
kmodule.xml
设置
resources/META-INF/kmodule.xml
<?xml version="1.0" encoding="UTF-8"?>
<kmodule xmlns="http://www.drools.org/xsd/kmodule">
<kbase name="rules" packages="rules">
<ksession name="hello-rules"/>
</kbase>
</kmodule>
注意
hello-rules
与Application
代码中的一致
- 规则文件
resources/rules/test.drl
package rules;
rule "test"
when
then
System.out.println("Hello World!");
end
注意这里的目录
rules
要与kmodule.xml
中的package="rules"
保持一致
- 执行Application(标准的Spring Boot项目启动)
Demo
- 实体类(
Person.java
)
@Data
@AllArgsConstructor
public class Person {
private String name;
private Integer age;
private Boolean gender;
}
- Application(
DroolsApplication.java
)
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
System.out.println("start to run task");
KieServices kieServices = KieServices.Factory.get();
KieContainer kieContainer = kieServices.newKieClasspathContainer();
Person tenmao = new Person("tenmao", 20, true);
Person bill = new Person("bill", 17, false);
KieSession kieSession = kieContainer.newKieSession("hello-rules");
kieSession.insert(tenmao);
kieSession.insert(bill);
kieSession.fireAllRules();
kieSession.destroy();
};
}
- 规则(
test.drl
)
package rules;
import com.tenmao.drools.Person
rule "test"
when
#过滤年龄大于18岁的
$p: Person(age > 18)
then
#输出
System.out.println($p);
end
- 执行Application(标准的Spring Boot项目启动)