Java-springboot集成+drools规则引擎集成,动态化编程

2024-03-25 10:36

本文主要是介绍Java-springboot集成+drools规则引擎集成,动态化编程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

drools+springboot集成

添加drools相关pom依赖
		// 第一种:kie-spring 整体引入<dependency><groupId>org.kie</groupId><artifactId>kie-spring</artifactId><version>${kie.version}</version></dependency><dependency><groupId>org.drools</groupId><artifactId>drools-core</artifactId><version>${kie.version}</version></dependency>// 第二种:单独引入<!-- drools依赖 --><properties><drools.version>7.24.0.Final</drools.version></properties><dependency><groupId>org.drools</groupId><artifactId>drools-core</artifactId><version>${drools.version}</version></dependency><dependency><groupId>org.drools</groupId><artifactId>drools-compiler</artifactId><version>${drools.version}</version></dependency><!-- 决策表 --><dependency><groupId>org.drools</groupId><artifactId>drools-decisiontables</artifactId><version>${drools.version}</version></dependency><!-- 模板 --><dependency><groupId>org.drools</groupId><artifactId>drools-templates</artifactId><version>${drools.version}</version></dependency><dependency><groupId>org.kie</groupId><artifactId>kie-api</artifactId><version>${drools.version}</version></dependency>
创建Kie相关 Bean 使其被spring管理
@Configuration
public class KiaSessionConfig {private static final String RULES_PATH = "rules/";@Beanpublic KieFileSystem kieFileSystem() throws IOException {KieFileSystem kieFileSystem = getKieServices().newKieFileSystem();for (Resource file : getRuleFiles()) {kieFileSystem.write(ResourceFactory.newClassPathResource(RULES_PATH + file.getFilename(), "UTF-8"));}return kieFileSystem;}private Resource[] getRuleFiles() throws IOException {ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();final Resource[] resources = resourcePatternResolver.getResources("classpath*:" + RULES_PATH + "**/*.*");return resources;}@Beanpublic KieContainer kieContainer() throws IOException {final KieRepository kieRepository = getKieServices().getRepository();kieRepository.addKieModule(new KieModule() {public ReleaseId getReleaseId() {return kieRepository.getDefaultReleaseId();}});KieBuilder kieBuilder = getKieServices().newKieBuilder(kieFileSystem());kieBuilder.buildAll();return getKieServices().newKieContainer(kieRepository.getDefaultReleaseId());}private KieServices getKieServices() {return KieServices.Factory.get();}@Beanpublic KieBase kieBase() throws IOException {return kieContainer().getKieBase();}@Beanpublic KieSession kieSession() throws IOException {return kieContainer().newKieSession();}
}
创建实体对象People
@Data
public class People {private int sex;private String name;private String drlType;public People(int sex, String name, String drlType) {this.sex = sex;this.name = name;this.drlType = drlType;}public People() {}
}
创建规则文件
package com.lvyuanj.micro.updat
dialect "java"
import com.lvyuanj.micro.entity.Peoplerule 'update1'when$p : People(drlType == "update" && sex == 0)thenSystem.out.println("update1执行====" + $p);$p.setSex(1);update($p)end
rule 'update2'when$p : People(drlType == "update" && sex == 1)thenSystem.out.println("update2执行====" + $p);endrule 'modify'when$p : People(drlType == "update" && sex == 1)thenSystem.out.println("update3执行====" + $p);modify($p){setSex(-1)}end
创建测试方法
@SpringBootTest
@RunWith(SpringRunner.class)
class DroolsApplicationTests {@Autowiredprivate KieSession session;@Autowiredprivate KieBase kieBase;@Testpublic void people() {People people = new People();people.setName("sun");people.setSex(1);people.setDrlType("people");session.insert(people);//插入session.fireAllRules();//执行规则}@AfterEachpublic void runDispose() {session.dispose();//释放资源}
}
drl文件结构
  1. package 包充当每组规则的唯一名称空间。一个规则库可以包含多个程序包。
    通常,将包的所有规则与包声明存储在同一文件中,以便包是独立的。但是,
    也可以在规则中使用从其他的包中导入的对象

  2. imports 与Java中的import语句类似,用来标识在规则中使用的任何对象的标准路径和类型名称

  3. factions 函数代码块如:

    function String hello(String applicantName) {return "Hello " + applicantName + "!";
    }
    
  4. queries 在Drools引擎的工作内存中搜索与DRL文件中的规则相关的事实

    query "people under the age of 21"$person : Person( age < 21 )
    end
    
    5. global 为规则提供数据或服务
    
2.1 rules 规则
属性描述
salience定义规则优先级的整数,数值越大,优先级越高
enabled规则启用开关
date-effective包含日期和时间定义的字符串。仅当当前日期和时间在date-effective属性之后时,才能激活该规则。
date-expires如果当前日期和时间在date-expires属性之后,则无法激活该规则。
no-loop选择该选项后,如果规则的结果重新触发了先前满足的条件,则无法重新激活(循环)规则。如果未选择条件,则在这些情况下可以循环规则。
agenda-group标识要向其分配规则的议程组
activation-group激活组,在激活组中,只能激活一个规则。触发的第一个规则将取消激活组中所有规则的所有未决激活。
duration定义了如果仍满足规则条件,则可以激活规则的持续时间(以毫秒为单位)。
timercron定时表达式
calendar时钟
auto-focus仅适用于议程组中的规则。选择该选项后,下次激活该规则时,将自动将焦点分配给分配了该规则的议程组。
lock-on-activeno-loop属性的更强版
ruleflow-group标识规则流组的字符串
dialect用于标识规则中的代码表达式JAVA或MVEL将其用作语言
2.2 匹配模式

2.2.1 没有约束的匹配模式

实事不需要满足任何条件,若类型相同,则触发该规则,如:

package com.ytooo.bean
import com.ytooo.bean.People
dialect  "java"rule "girl"whenPeople()thenSystem.out.println("girl规则执行");
end

2.2.2 有条件约束的匹配模式
实事类型相同,且满足条件,则触发该规则,如:

package com.ytooo.bean
import com.ytooo.bean.People
dialect  "java"rule "girl"whenPeople(sex == 0 && drlType == "people")thenSystem.out.println("girl规则执行");
end

2.2.3 匹配并绑定属性以及实事

实事类型相同,且满足条件,则触发该规则,并绑定数据,如:

package com.ytooo.bean
import com.ytooo.bean.People
dialect  "java"rule "girl"when$p:People(sex == 0,$sex : sex && drlType == "people")thenSystem.out.println("girl规则执行");System.out.println($p);System.out.println($sex);
end

2.3 条件
and,or 等结合规则条件的多个模式,没有定义关键字连词,默认是and:

package com.ytooo.bean
import com.ytooo.bean.People
import com.ytooo.bean.Cat
dialect  "java"rule "girl"whenPeople(sex == 0) andCat(sex == 0)thenSystem.out.println("girl规则执行");
end

2.4 约束

标准Java运算符优先级适用于DRL中的约束运算符,而drl运算符除==和!=运算符外均遵循标准Java语义。

在drl中 Person( firstName != “John” )类似于 !java.util.Objects.equals(person.getFirstName(), “John”)

约束描述
!.使用此运算符可以以空安全的方式取消引用属性。!.运算符左侧的值不能为null(解释为!= null)
[]按List索引访问值或Map按键访问值
<,<=,>,>=在具有自然顺序的属性上使用这些运算符
==, !=在约束中使用这些运算符作为equals()和!equals()方法
&&,||组合关系条件
matches,not matches使用这些运算符可以指示字段与指定的Java正则表达式匹配或不匹配
contains,not contains使用这些运算符可以验证Array或字段是否包含或不包含指定值
memberOf,not memberOf使用这些运算符可以验证字段是否为定义为变量Array的成员
soundslike使用英语发音来验证单词是否具有与给定值几乎相同的声音(类似于该matches运算符)
in,notin使用这些运算符可以指定一个以上的可能值来匹配约束(复合值限制)

2.4.1 约束
matches, not matches

Person( country matches "(USA)?\\S*UK" )
Person( country not matches "(USA)?\\S*UK" )

matches, not matches

FamilyTree(countries contains "UK" )
Person( fullName not contains "Jr" )
FamilyTree(countries contains $var)
Person( fullName not contains $var )

matches, not matches

FamilyTree( person memberOf $europeanDescendants )
FamilyTree( person not memberOf $europeanDescendants )

2.5 集合

package com.ytooo.bean;
import lombok.Data;
import java.util.List;/*** */
@Data
public class Animal {private Integer level;private List<People> peoples;}

2.5.1 from 取集合中的元素

/*** */
@Data
public class Animal {private Integer level;private List<People> peoples;}

新建from.drl

package com.lvyuanj.micro.frm
dialect "java"
import com.lvyuanj.micro.entity.People
import com.lvyuanj.micro.entity.Animalrule "from"
when$an : Animal()$p : People(sex != 3 && drlType == "from") from $an.peoplesthenSystem.out.println($p);end

新建测试方法

@Test
public void from() {People p1 = new People(1,"达","from");People p2 = new People(0,"秋","from");People p3 = new People(3,"金","from");Animal animal = new Animal();animal.setPeoples(new ArrayList<>());animal.getPeoples().add(p1);animal.getPeoples().add(p2);animal.getPeoples().add(p3);session.insert(animal);//插入session.fireAllRules();//执行规则
}

2.5.2 collect

从指定来源或从Drools引擎的工作内存中获取集合,可以使用Java集合(例如List,LinkedList和HashSet)

这篇关于Java-springboot集成+drools规则引擎集成,动态化编程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/844718

相关文章

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav