Spring Boot 中使用 Drools 规则引擎的完整步骤

 更新时间:2025年04月30日 10:33:12   作者:SteveCode.  
规则引擎主要用于将业务逻辑从应用程序代码中分离出来,提高系统的灵活性和可维护性,规则引擎通过预定义的规则来处理输入数据并做出相应的决策,从而实现业务逻辑的自动化和动态调整,本文给大家介绍Spring Boot中使用 Drools 规则引擎的指南,感兴趣的朋友一起看看吧

规则引擎作用

规则引擎主要用于将业务逻辑从应用程序代码中分离出来,提高系统的灵活性和可维护性。规则引擎通过预定义的规则来处理输入数据并做出相应的决策,从而实现业务逻辑的自动化和动态调整。

例如

门店信息校验:美团点评在门店信息校验过程中使用规则引擎,对门店信息进行质量控制。规则包括分支条件、简单计算规则和业务定制计算规则等。通过规则引擎,门店信息校验过程变得更加高效和准确。 业务场景说明

不同会员的折扣率不同

代码结构

集成 Drools(即规则引擎)到 Spring Boot 可以帮助你实现业务规则的动态管理和执行。下面我来简要说明一下业务场景和代码实现的步骤:

1. 添加依赖

首先,需要在 pom.xml 文件中添加 Drools 的依赖:

 <!-- drools规则引擎 -->
        <dependency>
            <groupId>org.drools</groupId>
            <artifactId>drools-compiler</artifactId>
            <version>7.6.0.Final</version>
        </dependency>

2. 创建规则文件

在项目的src/main/resources目录下创建一个名为rules的文件夹,并在其中创建一个名为sample.drl的规则文件:

package com.song;
import com.song.rulesobj.Customer
rule "ORDINARY-Customers"
when
    customer: Customer(type == "ORDINARY")
then
    customer.setDiscount(0.9*customer.getOriginalPrice()); // 9折  普通会员
end
rule "VIP-Customers"
when
    customer: Customer(type == "VIP")
then
    customer.setDiscount(0.6*customer.getOriginalPrice()); // 6折 VIP会员
end
rule "SVIP-Customers"
when
    customer: Customer(type == "SVIP")
then
    customer.setDiscount(0.4*customer.getOriginalPrice()); // 4折 SVIP会员
end

3. 定义实体类

创建一个简单的实体类 Customer,用于表示客户信息:

package com.song.rulesobj;
import lombok.Data;
@Data
public class Customer {
    /**
     * 客户类型
     */
    private String type;
    /**
     * 客户订单价格
     */
    private Double  originalPrice; // 订单原始价格,即优惠前的价格
    /**
     * 优惠后最终结算价格
     */
    private Double discount;
}

4. 配置 Drools 规则引擎

在 Spring Boot 应用程序中配置 Drools 规则引擎的 bean:

package com.song.conf;
import com.song.bean.DiscountBean;
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.api.runtime.KieSession;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DroolsConfig {
    @Bean
    public KieContainer kieContainer() {
        KieServices kieServices = KieServices.Factory.get();
        KieRepository kieRepository = kieServices.getRepository();
        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
        kieFileSystem.write(kieServices.getResources().newClassPathResource("rules/sample.drl"));
        KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
        kieBuilder.buildAll();
        return kieServices.newKieContainer(kieRepository.getDefaultReleaseId());
    }
    @Bean
    public KieSession kieSession() {
        return kieContainer().newKieSession();
    }
    @Bean
    public DiscountBean discountBean() {
       return new  DiscountBean(kieSession());
    }
}

5. 应用规则引擎

在业务代码中使用注入的 KieSession 执行规则:

/*******************************************************************************
 * Package: com.song.bean
 * Type:    DiscountService
 * Date:    2024-06-28 13:45
 *
 * Copyright (c) 2024 LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.bean;
import com.song.rulesobj.Customer;
import org.kie.api.runtime.KieSession;
/**
 * 功能描述: 规则处理器封装
 *
 * @author Songxianyang
 * @date 2024-06-28 13:45
 */
public class DiscountBean {
    private KieSession kieSession;
    public DiscountBean(KieSession kieSession) {
        this.kieSession = kieSession;
    }
    public void applyDiscount(Customer customer) {
        kieSession.insert(customer); // 插入客户对象到规则引擎中
        kieSession.fireAllRules(); // 执行规则
        // 客户对象已经被更新,包含了计算出的折扣
        System.out.println("客户订单价格"+customer.getOriginalPrice()+"客户折扣类型: " + customer.getType() + ", 优惠后最终结算价格: " + customer.getDiscount());
    }
}

6. 测试规则引擎

编写一个简单的测试类来验证规则引擎是否按预期工作:

package com.song.web;
import com.song.bean.DiscountBean;
import com.song.common.annotation.ResponseInfoSkin;
import com.song.rulesobj.Customer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Api(tags = "规则引擎")
@ResponseInfoSkin
public class DemoController {
    @Autowired
    private DiscountBean discountBean;
    @PostMapping("/discount")
    @ApiOperation("打折")
    public Double discount(@RequestBody Customer customer) {
        // 规则处理器封装
        discountBean.applyDiscount(customer);
        return customer.getDiscount();
    }
}

测试截图

总结

通过上述步骤,你可以将 Drools 规则引擎集成到 Spring Boot 应用程序中,并使用规则文件动态管理业务规则,实现不同客户类型的动态折扣计算。这种方式可以使得业务规则更易于维护和修改,同时与应用程序解耦,提高了灵活性和可维护性。

源码

到此这篇关于Spring Boot 中使用 Drools 规则引擎的完整指南的文章就介绍到这了,更多相关Spring Boot Drools 规则引擎内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 老生常谈java中的fail-fast机制

    老生常谈java中的fail-fast机制

    下面小编就为大家带来一篇老生常谈java中的fail-fast机制。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-08-08
  • java实现ssh连接服务器的方法步骤

    java实现ssh连接服务器的方法步骤

    本文主要介绍了java实现ssh连接服务器的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-09-09
  • Java中的vector类使用示例小结

    Java中的vector类使用示例小结

    Vector与ArrayList的实现基本相似,同样是基于动态数组,同样是需要扩容,下面举了三个简短的例子来帮助大家理解vertor:
    2016-05-05
  • SpringBoot接口数据如何实现优雅的脱敏问题

    SpringBoot接口数据如何实现优雅的脱敏问题

    这篇文章主要介绍了SpringBoot接口数据如何实现优雅的脱敏问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-12-12
  • SpringAop自定义切面注解、自定义过滤器及ThreadLocal详解

    SpringAop自定义切面注解、自定义过滤器及ThreadLocal详解

    这篇文章主要介绍了SpringAop自定义切面注解、自定义过滤器及ThreadLocal详解,Aspect(切面)通常是一个类,里面可以定义切入点和通知(切面 = 切点+通知),execution()是最常用的切点函数,需要的朋友可以参考下
    2024-01-01
  • SpringBoot整合MongoDB流程详解

    SpringBoot整合MongoDB流程详解

    这篇文章主要介绍了SpringBoot整合MongoDB流程详解,MongoDB是一种面向文档的数据库管理系统,它是一个介于关系型数据库和非关系型数据库之间的产品,MongoDB支持一种类似JSON的BSON数据格式,既可以存储简单的数据格式,也可以存储复杂的数据类型,需要的朋友可以参考下
    2024-01-01
  • MyBatis中example.createCriteria()方法的具体使用

    MyBatis中example.createCriteria()方法的具体使用

    本文详细介绍了MyBatis的Example工具的使用方法,包括链式调用指定字段、设置查询条件、支持多种查询方式等,还介绍了mapper的crud方法、and/or方法的使用,以及如何进行多条件和多重条件查询,感兴趣的可以了解一下
    2024-10-10
  • Spring Jms 模块案例讲解

    Spring Jms 模块案例讲解

    本文详细介绍了Spring-JMS模块,包括其核心功能和作用,通过ActiveMQ作为消息代理,提供了一个基于XML配置的完整示例,帮助开发者快速掌握Spring-JMS的使用方式,感兴趣的朋友一起看看吧
    2025-02-02
  • java中json-diff简单使用及对象是否一致详解

    java中json-diff简单使用及对象是否一致详解

    这篇文章主要为大家介绍了java中json-diff简单使用及对象是否一致对比详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-03-03
  • JAVA实现DOC转PDF的示例代码

    JAVA实现DOC转PDF的示例代码

    Word作为目前主流的文本编辑软件之一,功能十分强大,但是在传输的时候不稳定,那么如何从DOC转PDF,本文就来介绍一下,感兴趣的可以了解一下
    2021-08-08

最新评论