Drools 规则引擎
官网:https://www.drools.org/
累了听听歌:http://www.hy57.com/p/158102.html
1. 快速度入门
1. 导入依赖
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><!--drools规则引擎--><dependency><groupId>org.drools</groupId><artifactId>drools-core</artifactId><version>7.6.0.Final</version></dependency><dependency><groupId>org.drools</groupId><artifactId>drools-compiler</artifactId><version>7.6.0.Final</version></dependency><dependency><groupId>org.drools</groupId><artifactId>drools-templates</artifactId><version>7.6.0.Final</version></dependency><dependency><groupId>org.kie</groupId><artifactId>kie-api</artifactId><version>7.6.0.Final</version></dependency><dependency><groupId>org.kie</groupId><artifactId>kie-spring</artifactId><version>7.6.0.Final</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>RELEASE</version><scope>compile</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency></dependencies>
2. 创建实体类Ord
package com.dxw.pojo;public class Ord {public int getAmout() {return amout;}@Overridepublic String toString() {return "Ord{" +"amout=" + amout +", score=" + score +'}';}public void setAmout(int amout) {this.amout = amout;}public int getScore() {return score;}public void setScore(int score) {this.score = score;}private int amout;private int score;}
3. resources文件下创建 META-INF and rules文件夹
1.META-INF文件夹
下面创建 kmodule.xml 文件
kmodule.xml配置如下
<?xml version="1.0" encoding="UTF-8" ?>
<kmodule xmlns="http://www.drools.org/xsd/kmodule">
<kbase name="myKbase1" packages="rules" declarativeAgenda="true">
<ksession name="ksession-rele" default="true"/>
</kbase>
</kmodule>
3. rules 文件夹
创建 score-relus.drl 文件
score-relus.drl配置如下(业务实际需求)
@Testpublic void tet(){KieServices kieServices = KieServices.Factory.get();KieContainer kieClasspathContainer = kieServices.getKieClasspathContainer();KieSession kieSession = kieClasspathContainer.newKieSession();Ord ord = new Ord();ord.setAmout(12);kieSession.insert(ord);kieSession.fireAllRules();kieSession.dispose();System.out.println(ord.getScore());}
2. 整合spring-boot
1. config配置类 ( 固定写法 )
package com.example.demo.drools.config;import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.kie.api.runtime.KieContainer;
import org.kie.internal.io.ResourceFactory;
import org.kie.spring.KModuleBeanFactoryPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.Resource;
import java.io.IOException;import java.io.IOException;@Configuration
public class DroolsConfig {//指定规则⽂件存放的⽬录private static final String RULES_PATH = "rules/";private final KieServices kieServices = KieServices.Factory.get();@Bean@ConditionalOnMissingBeanpublic KieFileSystem kieFileSystem() throws IOException {//设置规则启动时间System.setProperty("drools.dateformat","yyyy-MM-dd");KieFileSystem kieFileSystem = kieServices.newKieFileSystem();ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();Resource[] files = resourcePatternResolver.getResources("classpath*:" + RULES_PATH + "*.*");String path = null;for (Resource file : files) {path = RULES_PATH + file.getFilename();kieFileSystem.write(ResourceFactory.newClassPathResource(path, "UTF-8"));}return kieFileSystem;}@Bean@ConditionalOnMissingBeanpublic KieContainer kieContainer() throws IOException {KieRepository kieRepository = kieServices.getRepository();kieRepository.addKieModule(kieRepository::getDefaultReleaseId);KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem());kieBuilder.buildAll();return kieServices.newKieContainer(kieRepository.getDefaultReleaseId());}@Bean@ConditionalOnMissingBeanpublic KieBase kieBase() throws IOException {return kieContainer().getKieBase();}@Bean@ConditionalOnMissingBeanpublic KModuleBeanFactoryPostProcessor kiePostProcessor() {return new KModuleBeanFactoryPostProcessor();}
}
2. 实体类
package com.example.demo.pojo;public class Order {private int amout;private int score;public int getAmout() {return amout;}public void setAmout(int amout) {this.amout = amout;}public int getScore() {return score;}public void setScore(int score) {this.score = score;}
}
3. 控制器
package com.example.demo.controller;import com.example.demo.pojo.Order;
import com.example.demo.service.RuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class OrderController {@Autowiredprivate RuleService ruleService;@GetMapping("/saveOrder")public Order saveOrder(Order order) {System.out.println("hello,world");return ruleService.executeOrderRule(order);}
}
4. service层
package com.example.demo.service;import com.example.demo.pojo.Order;import org.kie.api.KieBase;import org.kie.api.runtime.KieSession;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;
@Servicepublic
class RuleService {
@Autowired
private KieBase kieBase; /*** 执⾏订单⾦额积分规则 */
public Order executeOrderRule(Order order) {
KieSession kieSession = kieBase.newKieSession(); kieSession.insert(order); kieSession.fireAllRules();
kieSession.dispose();
return order;
}}
5. resources 文件
创建droolsd包
score-rules.drl文件
package rules
import com.example.demo.pojo.Order//规则1:100元以下, 不加分
rule "score_1"
when$s : Order(amout <= 100)
then$s.setScore(0);System.out.println("成功匹配到规则1:100元以下, 不加分 ");
end//规则2:100元-500元 加100分
rule "score_2"
when$s : Order(amout > 100 && amout <= 500)
then$s.setScore(100);System.out.println("成功匹配到规则2:100元-500元 加100分 ");
end//规则3:500元-1000元 加500分
rule "score_3"
when$s : Order(amout > 500 && amout <= 1000)
then$s.setScore(500);System.out.println("成功匹配到规则3:500元-1000元 加500分 ");
end//规则4:1000元 以上 加1000分
rule "score_4"
when$s : Order(amout > 1000)
then$s.setScore(1000);System.out.println("成功匹配到规则4:1000元 以上 加1000分 ");
en
static 创建 order.html
<!DOCTYPE >
<html lang="en">
<head><meta charset="UTF-8"><title>订单⻚⾯</title><script type="text/javascript" src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script><style> div {margin: auto;width: 500px;}#score {color: red;font-size: 14px;} </style>
</head>
<body>
<div><table><tr><td>订单⾦额:</td><td><input type="text" id="amout" name="amout"/></td></tr><tr><td>该订单可以累计的积分:</td><td><span id="score"></span></td></tr></table>
</div>
</body>
<script type="text/javascript">$(function () {$("#amout").blur(function () {$.ajax({url: "/saveOrder",type: "get",data: {"amout": $("#amout").val()},dataType: "json",success: function (data) {//设置积分$("#score").html(data.score);}});});});
</script>
</html>
3. Drools 实战(计算所得税)
创建 Calculation 类并且提供getset方法
public class Calculation {private double wage; //税前工资private double wagemore; //应纳税所得额private double cess; //税率private double preminus; //速算解扣除数private double wageminus; //扣税额}
编写 calculation.drl 规则文件
package rulesimport com.example.demo.pojo.Calculation
rule "计算应纳税所得额" //优先级 salience 10 //设置规则启动时间 date-effective "2022-10-21" //防止死循环 no-loop true when $cal: Calculation(wage > 0) then double wagemore = $cal.getWage() - 3500; //赋值 $cal.setWagemore(wagemore); update($cal)endrule "设置税率,速算扣除数 >1500 and <=4500"
salience 9 no-loop true //方法不重复触发
activation-group "SETCess_Group" when
$cal:Calculation(wagemore > 1500 && wagemore<=5400)
then $cal.setCess(0.1); //税率 $cal.setPreminus(105); //速算扣除数 update($cal);endrule "设置税率,速算扣除数 >4500 and <=10000"
salience 9 no-loop true activation-group "SETCess_Group"
when $cal:Calculation(wagemore > 4500 && wagemore<=10000) then $cal.setCess(0.2); //税率 $cal.setPreminus(305); //速算扣除数 update($cal);endrule "个人所得税:计算税后工资"
salience 1
when $cal:Calculation(wage > 0 && wagemore > 0 && cess > 0) then
double wageminus = $cal.getWagemore() * $cal.getCess() - $cal.getPreminus(); double actualwage = $cal.getWage() -wageminus; $cal.setWagemore(wageminus);
$cal.setActualwage(actualwage); System.out.println("税前工资"+$cal.getWage()); System.out.println("应纳税所得额"+$cal.getWagemore()); System.out.println("税率"+$cal.getCess()); System.out.println("速算扣除数"+$cal.getPreminus()); System.out.println("税后工资"+$cal.getActualwage());end
RuleService 层
@Autowiredprivate KieBase kieBase;public Calculation calculation(Calculation calculation) {KieSession kieSession = kieBase.newKieSession();kieSession.insert(calculation);kieSession.fireAllRules();kieSession.dispose();return calculation;}
OrderController 类
@RequestMapping("/calculate")public Calculation calculation(double wage){Calculation calculation = new Calculation();calculation.setWage(wage);Calculation calculation1 = ruleService.calculation(calculation);return calculation1;}
最后,自己传入参数测试!!!
Drools 规则引擎相关推荐
- 详解:Drools规则引擎探究
引入 ▐ 问题引入 天猫奢品业务方为了吸引更多的新客,和提高会员的活跃度,做了一期活动,通过购买天猫奢品频道内的任意商品就赠送特殊积分,积分可以直接兑换限量的奢品商品.假如业务方给的规则如下: 主刃同 ...
- 使用 Drools 规则引擎实现业务逻辑,可调试drl文件
http://www.srcsky.com/tech/arts/389.html 代码下载http://download.csdn.net/detail/zhy011525/2462313 使用 Dr ...
- drools规则引擎因为内存泄露导致的内存溢出
进入这个问题之前,先了解一下drools: 在很多行业应用中比如银行.保险领域,业务规则往往非常复杂,并且规则处于不断更新变化中,而现有很多系统做法基本上都是将业务规则绑定在程序代码中. 主要存在的问 ...
- SpringBoot2 整合 Drools规则引擎,实现高效的业务规则
本文源码:GitHub·点这里 || GitEE·点这里 一.Drools引擎简介 1.基础简介 Drools是一个基于java的规则引擎,开源的,可以将复杂多变的规则从硬编码中解放出来,以规则脚本的 ...
- SpringBoot整合Drools规则引擎动态生成业务规则
最近的项目中,使用的是flowable工作流来处理业务流程,但是在业务规则的配置中,是在代码中直接固定写死的,领导说这样不好,需要规则可以动态变化,可以通过页面去动态配置改变,所以就花了几天时间去研究 ...
- drools规则引擎 java_Drools规则引擎的使用总结
前一段时间在开发了一个做文本分析的项目.在项目技术选型的过程中,尝试使用了Drools规则引擎.让它来作为项目中有关模式分析和关键词匹配的任务.但后来,因为某种原因,还是撇开了Drools.现将这个过 ...
- 大数据风控项目实战 Drools规则引擎
可以借鉴的干货 1,统一存储服务,包含:多种存储库连接封装和服务封装 在统一存储服务 2.获取配置的环境 类:EnvVariable 一.风控项目介绍 对一个复杂支付系统提供统一.全面.高效的风险控制 ...
- drools规则引擎动态配置规则
先说下我的业务需求背景,最近公司要推出运营活动,根据用户行为送用户积分:比如用户注册送.首次消费送,非首次消费送.累积消费送.针对我们这个的特殊要求是跟具体规则绑定:比如说 规则1 用户累积消费首次达 ...
- Drools规则引擎-memberOf操作
场景 规则引擎技术讨论2群(715840230)有同学提出疑问,memberOf的使用过程中如果,memberOf之后的参数不是集合也不是数组,而是格式如"1,2,3,4"的字符串 ...
- Drools规则引擎之常用语法
一.基础api 在 Drools 当中,规则的编译与运行要通过Drools 提供的各种API 来实现,这些API 总体来讲可以分为三类:规则编译.规则收集和规则的执行.完成这些工作的API 主要有Kn ...
最新文章
- Facebook人工智能实验室提出「全景分割」,实现实例分割和语义分割的统一
- django基本操作
- java 获取400的错误信息_获取400错误的请求Spring RestTemplate POST
- java 关键字volatile的作用
- 逆向工程核心原理学习笔记(十一):栈
- 03-JavaScript
- python对象三个特性_百度资讯搜索_python对象三个特性
- 两数的和与差的简单函数
- 50条大牛C++编程开发学习建议
- SpringBoot-视图解析与模板引擎
- 华为nova9 SE官网上架:华为首款1亿像素手机
- gtihub第二次上传项目_国道岱山项目双合大桥墩柱桩基打桩施工突破100根
- 天闻角川超人气IP「画猫·雅宋」数字藏品限量开售!
- sentaurus TCAD的安装与使用
- Raul的新机器学习书!
- 康师傅被“水和面”糊住了眼睛?
- 图片格式网页在线一键转换源码
- 移动端图片居多,加载过慢,使用延迟加载|懒加载( lazyload.js)
- javax.servlet.ServletException: Could not resolve view with name ‘***‘ in servlet
- 什么是Perl语言?
热门文章
- HTML5期末大作业:水果商城网站设计——蔬菜水果商城(10页) HTML+CSS+JavaScript 学html网页制作期末大作业成品_网页设计期末作业
- 拼多多的服务器需要维护吗,拼多多客服外包 店铺评价如何维护 外包客服分享几个小秘诀...
- IDEA中将maven项目导出打包成war包
- 画质增强概述-4-传统方法增强实践
- 【数据结构与算法图文动画详解】终于可以彻底弄懂:红黑树、B-树、B+树、B*树、满二叉树、完全二叉树、平衡二叉树、二叉搜索树...
- python制作短视频_只要三步,用Python轻松制作短视频,你也能在朋友圈傲娇一把!...
- 「学习笔记」Vue 官方视频教程 2.0版
- 一文带你彻底了解IIC协议
- 电脑开机出现蓝屏英文怎么办?简单一招带你解决
- 工控计算机 isa接口,工控机常见的几种外设和接口