实现需求:
年龄>=18可以玩游戏,否则不可以玩游戏
整体文件目录结构如下
1 pom.xml
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-bom</artifactId>
<type>pom</type>
<version>7.69.0.Final</version>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-compiler</artifactId>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-mvel</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
</dependencies>
2 drools配置文件
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DroolsConfig {
@Bean
public KieContainer kieContainer() {
KieServices kieServices = KieServices.get();
return kieServices.getKieClasspathContainer();
}
}
3 META-INF/kmodule.xml 文件编写
<kmodule xmlns="http://www.drools.org/xsd/kmodule">
<kbase name="kabse" packages="rules" default="false">
<ksession name="ksession" default="false" type="stateful">
<consoleLogger/>
<listeners>
<ruleRuntimeEventListener type="org.kie.api.event.rule.DebugRuleRuntimeEventListener"/>
<processEventListener type="org.drools.core.event.DebugProcessEventListener"/>
<agendaEventListener type="org.drools.core.event.DebugAgendaEventListener"/>
</listeners>
</ksession>
</kbase>
</kmodule>
4 rules/rule1.drl规则文件编写
package rules
import cn.beijing.model.Person
// 用户可以玩游戏
rule "用户可以玩游戏"
when
$person: Person( age >= 18)
then
$person.setCanPlayGame(true);
System.out.println("触发规则:" + drools.getRule().getName());
end
// 用户不可以玩游戏
rule "用户不可以玩游戏"
when
$person: Person( age < 18)
then
$person.setCanPlayGame(false);
System.out.println("触发规则:" + drools.getRule().getName());
end
5 pojo文件
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Person {
private String name;
private Integer age;
// 是否可以玩游戏,此字段的值,由 drools 引擎计算得出
private Boolean canPlayGame;
}
6 调用测试
import cn.beijing.model.Person;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PersonController {
@Autowired
private KieContainer kieContainer;
/**
* 调用drools rule判断用户是否可以玩游戏
*/
@GetMapping("canPlayGame")
public Person canPlayGame(Person person) {
//编译规则,通过的话,生成会话
KieSession kieSession = kieContainer.newKieSession("ksession");
try {
//插入数据,执行规则
kieSession.insert(person);
//执行规则
kieSession.fireAllRules();
} finally {
//释放资源
kieSession.dispose();
}
return person;
}
}