【三十四】springboot+easyRule初识规则引擎

2024-08-31 17:20

本文主要是介绍【三十四】springboot+easyRule初识规则引擎,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

        代码场景:厂里有几个员工,现在厂长颁布了新的厂规关于薪资发放,如下:

  • 1、加班时长超过80小时的,一个小时10块钱;不满80小时的,不算加班。
  • 2、上班打卡迟到3次以下的不扣钱,3次以上的一次扣100。

        针对如上需求,是不是就可以通过写if-if判断来处理,但是如果规则变化呢,老板想只要迟到1次就扣1000,或者只要加班就100块钱一个小时呢,是不是只有改代码升级。 本章针对这个问题,通过规则引擎实现这个场景,实现规则配置化。

目录

一、准备工作

二、注解方式实现

三、yml配置方式实现


一、准备工作

1、表

2、依赖
<dependency><groupId>org.jeasy</groupId><artifactId>easy-rules-core</artifactId><version>4.1.0</version></dependency><dependency><groupId>org.jeasy</groupId><artifactId>easy-rules-mvel</artifactId><version>4.1.0</version></dependency><dependency><groupId>org.jeasy</groupId><artifactId>easy-rules-spel</artifactId><version>4.1.0</version></dependency><dependency><groupId>org.jeasy</groupId><artifactId>easy-rules-jexl</artifactId><version>4.1.0</version></dependency>

二、注解方式实现

1、编写目的场景的规则
@Rule(name = "无效加班", description = "加班费的结算", priority = 1)
public class Rule1 {@Conditionpublic boolean when(@Fact("time") double time) {return time<=80;}@Actionpublic void then(@Fact("reason") StringBuffer reason) {reason.append("加班少于80小时,不发加班费;");}}
@Rule(name = "有效加班", description = "加班费的结算", priority = 2)
public class Rule2 {@Conditionpublic boolean when(@Fact("time") double time) {return time > 80;}@Actionpublic void then(@Fact("time") double time,@Fact("reason") StringBuffer reason,@Fact("money") AtomicDouble money) {money.set(money.get()+10*(time-80));reason.append("加班费:").append(10*(time-80)).append(";");}}
@Rule(name = "迟到警告", description = "迟到的惩罚", priority = 3)
public class Rule3 {@Conditionpublic boolean when(@Fact("count") int count) {return count<=3;}@Actionpublic void then(@Fact("count") int count, @Fact("money") AtomicDouble money, @Fact("reason") StringBuffer reason) {reason.append("迟到小于3次,暂时不扣钱;");}}
@Rule(name = "迟到扣钱", description = "迟到的惩罚", priority = 3)
public class Rule4 {@Conditionpublic boolean when(@Fact("count") int count) {return count>3;}@Actionpublic void then(@Fact("count") int count, @Fact("money") AtomicDouble money, @Fact("reason") StringBuffer reason) {money.set(money.get() - (count-3)*100);reason.append("迟到大于3次,扣钱:").append((count - 3) * 100).append(";");}}
  • @Rule标识该类为规则类
  • @Condition标识该方法为条件(一个rule类只能有一个) 
  • @Action标识该方法为条件满足为true后的执行方法
  • @Fact代表事实,标识入参,可以通过Fact的key值获取值
  • priority标识该rule的执行顺序
2、编写接口
@Slf4j
@Api(tags = "牛马管理接口")
@RestController
@RequestMapping("/staffController")
@AllArgsConstructor
public class StaffController {private final StaffMapper staffMapper;@ApiOperation(value = "计算工资")@PostMapping("/getSalary")public BaseResponse<Integer> getSalary() {// 初始化规则引擎RulesEngineParameters parameters = new RulesEngineParameters().skipOnFirstAppliedRule(false);DefaultRulesEngine engine = new DefaultRulesEngine(parameters);engine.registerRuleListener(new MyRuleListener());// 注册规则进入引擎Rules rules = new Rules();rules.register(new Rule1());rules.register(new Rule2());rules.register(new Rule3());rules.register(new Rule4());//UnitRuleGroup unitRuleGroup = new UnitRuleGroup("myUnitRuleGroup", "myUnitRuleGroup");//unitRuleGroup.addRule(new Rule1());//unitRuleGroup.addRule(new Rule2());//unitRuleGroup.addRule(new Rule3());//unitRuleGroup.addRule(new Rule4());//rules.register(unitRuleGroup);List<Staff> list = staffMapper.selectList(new QueryWrapper<>());for (Staff staff : list) {AtomicDouble money = new AtomicDouble((Double.parseDouble(staff.getMoney())));double beforeMoney = money.get();StringBuffer reason = new StringBuffer();Facts facts = new Facts();facts.put("time", Double.parseDouble(staff.getTime()));facts.put("count", staff.getCount());facts.put("money", money);facts.put("reason", reason);engine.fire(rules, facts);Staff staffNew = staffMapper.selectById(staff.getId());staffNew.setFinalMoney(facts.get("money").toString());staffNew.setDetail(reason.toString());staffMapper.updateById(staffNew);}return RespGenerator.returnOK("成功");}}
3、测试

根据结果可以看到数据正确。

现在假设我们厂长更改了需求:现在只要迟到超过3次,都没有加班费

        如上代码可以根据实际情况改造一下,当有需求所有规则要么全部执行,要么全部不执行时(只要有一个不满足就全部跳过执行),可以选用另一种方式UnitRuleGroup,改造如下:

@ApiOperation(value = "计算工资")@PostMapping("/getSalary")public BaseResponse<Integer> getSalary() {// 初始化规则引擎RulesEngineParameters parameters = new RulesEngineParameters().skipOnFirstAppliedRule(false);DefaultRulesEngine engine = new DefaultRulesEngine(parameters);engine.registerRuleListener(new MyRuleListener());// 注册规则进入引擎Rules rules = new Rules();//rules.register(new Rule1());//rules.register(new Rule2());//rules.register(new Rule3());//rules.register(new Rule4());UnitRuleGroup unitRuleGroup = new UnitRuleGroup("myUnitRuleGroup", "myUnitRuleGroup");//unitRuleGroup.addRule(new Rule1());unitRuleGroup.addRule(new Rule2());unitRuleGroup.addRule(new Rule3());//unitRuleGroup.addRule(new Rule4());rules.register(unitRuleGroup);List<Staff> list = staffMapper.selectList(new QueryWrapper<>());for (Staff staff : list) {AtomicDouble money = new AtomicDouble((Double.parseDouble(staff.getMoney())));double beforeMoney = money.get();StringBuffer reason = new StringBuffer();Facts facts = new Facts();facts.put("time", Double.parseDouble(staff.getTime()));facts.put("count", staff.getCount());facts.put("money", money);facts.put("reason", reason);engine.fire(rules, facts);Staff staffNew = staffMapper.selectById(staff.getId());staffNew.setFinalMoney(facts.get("money").toString());staffNew.setDetail(reason.toString());staffMapper.updateById(staffNew);}return RespGenerator.returnOK("成功");}

结果如下:

 可以看到赵四加班了一个小时也没有加班费了。

三、yml配置方式实现

1、增加配置文件
---
name: '无效加班'
description: '加班费的结算'
priority: 1
condition: "time<=80"
actions:- "reason.append('加班少于80小时,不发加班费;');"
---
name: '有效加班'
description: '加班费的结算'
priority: 2
condition: "time>80"
actions:- "money.set(money.get()+10*(time-80));reason.append('加班费:').append(10*(time-80)).append(';');"
---
name: '迟到警告'
description: '迟到的惩罚'
priority: 1
condition: "count<=3"
actions:- "reason.append('迟到小于3次,暂时不扣钱;');"
---
name: '迟到扣钱'
description: '迟到的惩罚'
priority: 2
condition: "count>3"
actions:- "money.set(money.get() - (count-3)*1000);reason.append('迟到大于3次,扣钱:').append((count - 3) * 1000).append(';');"

每个rule之间通过---进行分割,可以在condition和actions下写java代码。 

2、改造接口
@ApiOperation(value = "计算工资")@PostMapping("/getSalary")public BaseResponse getSalary() throws Exception {// 初始化规则引擎RulesEngineParameters parameters = new RulesEngineParameters().skipOnFirstAppliedRule(false);DefaultRulesEngine engine = new DefaultRulesEngine(parameters);engine.registerRuleListener(new MyRuleListener());// 注册规则进入引擎MVELRuleFactory ruleFactory = new MVELRuleFactory(new YamlRuleDefinitionReader());Rules rules = ruleFactory.createRules(new BufferedReader(new InputStreamReader(Objects.requireNonNull(this.getClass().getClassLoader().getResourceAsStream("rules.yml")))));List<Staff> list = staffMapper.selectList(new QueryWrapper<>());for (Staff staff : list) {AtomicDouble money = new AtomicDouble((Double.parseDouble(staff.getMoney())));double beforeMoney = money.get();StringBuffer reason = new StringBuffer();Facts facts = new Facts();facts.put("time", Double.parseDouble(staff.getTime()));facts.put("count", staff.getCount());facts.put("money", money);facts.put("reason", reason);engine.fire(rules, facts);Staff staffNew = staffMapper.selectById(staff.getId());staffNew.setFinalMoney(facts.get("money").toString());staffNew.setDetail(reason.toString());staffMapper.updateById(staffNew);}return RespGenerator.returnOK("成功");}

 

假设当我们调整加班费时(1块钱一个小时),修改配置即可。

name: '有效加班'
description: '加班费的结算'
priority: 2
condition: "time>80"
actions:- "money.set(money.get()+1*(time-80));reason.append('加班费:').append(1*(time-80)).append(';');"

这篇关于【三十四】springboot+easyRule初识规则引擎的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听

在cscode中通过maven创建java项目

在cscode中创建java项目 可以通过博客完成maven的导入 建立maven项目 使用快捷键 Ctrl + Shift + P 建立一个 Maven 项目 1 Ctrl + Shift + P 打开输入框2 输入 "> java create"3 选择 maven4 选择 No Archetype5 输入 域名6 输入项目名称7 建立一个文件目录存放项目,文件名一般为项目名8 确定