pom
依赖
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-compiler</artifactId>
<version>7.68.0.Final</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-mvel</artifactId>
<version>7.68.0.Final</version>
</dependency>
kmodule.xml
文件配置
kmodule.xml
文件必须在resource/META-INF
目录下创建,配置模板固定,内容如下:<?xml version="1.0" encoding="UTF-8"?>
<kmodule xmlns="http://www.drools.org/xsd/kmodule">
<kbase name="userBase" packages="rules" default="true">
<ksession name="userSession"/>
</kbase>
</kmodule>
drl
规则文件配置
在kmodule.xml
文件中指定的目录下创建drl
文件,在IDEA
中最好先安装好Drools
插件,文件内容如下:package rules;
import com.jin.bean.User
rule "r1"
when
$user:User(age == 20)
then
System.out.println("用户信息: " + $user.toString());
end
关于文件中的语法就不细说了,有点基础就应该能看懂- 代码
import com.jin.bean.User;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
public class DroolsDemo {
public static void main(String[] args) {
KieServices ks = KieServices.Factory.get();
KieContainer container = ks.getKieClasspathContainer();
KieSession session = container.newKieSession("session");
User build = User.builder().age(20).build();
session.insert(build);
int i = session.fireAllRules();
session.getIdentifier();
System.out.println("规则条数: " + i);
session.dispose();
}
}
- 控制台结果
[INFO] -org.drools.compiler.kie.builder.impl.KieContainerImpl -919 -org.drools.compiler.kie.builder.impl.KieContainerImpl.createKieBase(KieContainerImpl.java:487).createKieBase(487) | End creation of KieBase: HelloBase
用户信息: User(name=null, age=20, gender=null, hobbit=null)
规则条数: 1