当前位置:网站首页>规则引擎Drools的使用
规则引擎Drools的使用
2022-07-26 04:04:00 【抓手】
引入maven
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-templates</artifactId>
<version>7.14.0.Final</version>
</dependency>
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-spring</artifactId>
<version>7.14.0.Final</version>
</dependency>工具类封装
import org.kie.api.KieBase;
import org.kie.api.KieBaseConfiguration;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.conf.EventProcessingOption;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Map;
/**
* drools架构规则工具
*
* @author 向振华
* @date 2022/06/30 17:29
*/
public class KieUtils {
/**
* 执行全部规则
*
* @param entity 规则文件中的实体类
* @param globals 全局变量
* @param drl 规则文件
*/
public static void fireAllRules(Object entity, Map<String, Object> globals, String drl) {
//会话对象,用于和规则引擎交互
KieSession kieSession = getKieSession(entity, globals, drl);
//激活规则引擎,如果规则匹配成功则执行规则
kieSession.fireAllRules();
//关闭会话
kieSession.dispose();
}
/**
* 执行全部规则
*
* @param kSession
*/
public static void fireAllRules(KieSession kSession) {
//激活规则引擎,如果规则匹配成功则执行规则
kSession.fireAllRules();
//关闭会话
kSession.dispose();
}
/**
* 获取KieSession
*
* @param entity 规则文件中的实体类
* @param globals 全局变量
* @param drl 规则文件
* @return
*/
public static KieSession getKieSession(Object entity, Map<String, Object> globals, String drl) {
KieSession kieSession = getKieSession(drl);
kieSession.insert(entity);
if (!CollectionUtils.isEmpty(globals)) {
for (String key : globals.keySet()) {
kieSession.setGlobal(key, globals.get(key));
}
}
return kieSession;
}
/**
* 获取KieSession
*
* @param drls 规则文件
* @return
*/
public static KieSession getKieSession(String... drls) {
KieHelper kieHelper = new KieHelper();
for (String drl : drls) {
kieHelper.addContent(drl, ResourceType.DRL);
}
verify(kieHelper);
KieBaseConfiguration config = kieHelper.ks.newKieBaseConfiguration();
config.setOption(EventProcessingOption.STREAM);
KieBase kieBase = kieHelper.build(config);
//创建KieSession
return kieBase.newKieSession();
}
/**
* 校验规则文件
*
* @param drl 规则文件
*/
public static void verify(String drl) {
KieHelper kieHelper = new KieHelper();
kieHelper.addContent(drl, ResourceType.DRL);
verify(kieHelper);
}
/**
* 校验
*
* @param kieHelper
*/
private static void verify(KieHelper kieHelper) {
Results results = kieHelper.verify();
List<Message> messages = results.getMessages(Message.Level.WARNING, Message.Level.ERROR);
if (!CollectionUtils.isEmpty(messages)) {
StringBuilder error = new StringBuilder("规则文件错误 ");
for (Message message : messages) {
error.append(message.getText()).append(";");
}
throw new RuntimeException(error.toString());
}
}
}定义entity
/**
* @author 向振华
* @date 2022/06/30 16:11
*/
public class DemoEntity {
private String name;
private String remark;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public DemoEntity() {
}
public DemoEntity(String name) {
this.name = name;
}
@Override
public String toString() {
return "DemoEntity{" +
"name='" + name + '\'' +
", remark='" + remark + '\'' +
'}';
}
}创建规则文件demo.drl
package demo
import com.xzh.drools.entity.DemoEntity
rule "demo"
when
$demo:DemoEntity(name contains "小明")
then
$demo.setRemark("哈喽" + $demo.getName());
System.out.println("规则执行 ---> " + $demo.getRemark());
end测试
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class DemoTest {
@Test
public void test1() throws IOException {
DemoEntity entity = new DemoEntity("小明");
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
Resource resource = resourcePatternResolver.getResource("classpath:rules/demo.drl");
byte[] bytes = IOUtils.toByteArray(resource.getInputStream());
String drl = new String(bytes);
KieUtils.fireAllRules(entity, null, drl);
}
}结果
规则执行 ---> 哈喽小明边栏推荐
- Communication protocol and message format between microservices
- Basic line chart: the most intuitive presentation of data trends and changes
- Supervit for deep learning
- Experimental reproduction of image classification (reasoning only) based on caffe resnet-50 network
- Oracle 11g "password delayed verification" feature
- Leetcode: 102. Sequence traversal of binary tree
- 【二叉树】二叉树中的最长交错路径
- PHP installation spool supports dtls protocol
- redux
- What are the differences between vite and wenpack?
猜你喜欢

Go Plus Security:一款Build Web3不可或缺的安全生态基础设施

《opencv学习笔记》-- 边缘检测和canny算子、sobel算子、LapIacian 算子、scharr滤波器

General test case writing specification

在 Istio 服务网格内连接外部 MySQL 数据库

Summary of senior report development experience: understand this and do not make bad reports

Testing is not valued? Senior: you should think in another position

5年1.4W倍,NFT OG 的封神之路|Web3专栏

PHP method to find the location of session storage file

2021 CIKM |GF-VAE: A Flow-based Variational Autoencoder for Molecule Generation

Advanced content of MySQL -- three MySQL logs that must be understood binlog, redo log and undo log
随机推荐
Opencv learning notes -- Hough transform
How to use graffiti magic color product development kit
PHP method to find the location of session storage file
Uniapp pit filling Tour
触觉智能分享-RK3568在景区导览机器人中的应用
Summary of senior report development experience: understand this and do not make bad reports
PHP save array to var file_ export、serialize
Introduction to UFS CLK gate
Luoda development - audio stream processing - AAC / loopbacktest as an example
Leetcode: 102. Sequence traversal of binary tree
2021 CIKM |GF-VAE: A Flow-based Variational Autoencoder for Molecule Generation
2022杭电多校 Bowcraft
深度学习之DAT
1311_硬件设计_ICT概念、应用以及优缺点学习小结
[digital ic/fpga] Hot unique code detection
Save the image with gaussdb (for redis), and the recommended business can easily reduce the cost by 60%
Course selection information management system based on SSM
5 years, 1.4W times, NFT og's road to immortality Web3 column
深度学习之SuperViT
[Reading Notes - > data analysis] Introduction to BDA textbook data analysis