Solon-Flow规则引擎示例:构建智能业务决策系统

Solon-Flow规则引擎示例:构建智能业务决策系统

【免费下载链接】solon-flow Solon Flow 通用流程编排框架(采用 json 和 yaml 编排格式)。可用于计算(或任务)的编排场景; 可用于业务规则和决策处理型的编排场景; 可用于办公审批型(有状态、可中断,人员参与)的编排场景; 可用于长时间流程(结合自动前进,等待介入)的编排场景。 【免费下载链接】solon-flow 项目地址: https://gitcode.com/opensolon/solon-flow

还在为复杂的业务规则逻辑而头疼吗?每次需求变更都要修改大量硬编码的if-else语句?Solon-Flow规则引擎提供了一种优雅的解决方案,通过YAML配置实现灵活的业务规则编排,让规则管理变得简单高效。

读完本文,你将掌握:

  • ✅ Solon-Flow规则引擎的核心概念与架构
  • ✅ 基于YAML的规则配置实战示例
  • ✅ 多种表达式引擎的集成与选择
  • ✅ 复杂业务场景的规则编排技巧
  • ✅ 规则引擎的性能优化最佳实践

规则引擎架构解析

Solon-Flow规则引擎采用轻量级设计,核心架构如下:

mermaid

基础规则配置实战

图书折扣规则示例

首先创建一个图书订单类作为业务对象:

@Getter
@Setter
public class BookOrder {
    int originalPrice;  // 原价
    int realPrice;      // 实付价格
}

然后定义折扣规则配置文件 bookDiscount.chain.yml

id: "book_discount"
layout:
  - id: "book_discount_1"
    when: |
      order.getOriginalPrice() < 100
    task: |
      order.setRealPrice(order.getOriginalPrice());
      System.out.println("没有优惠");
      
  - id: "book_discount_2"
    when: |
      order.getOriginalPrice() < 200 && order.getOriginalPrice() >= 100
    task: |
      order.setRealPrice(order.getOriginalPrice() - 20);
      System.out.println("优惠20元");
      
  - id: "book_discount_3"
    when: |
      order.getOriginalPrice() >= 200 && order.getOriginalPrice() < 300
    task: |
      order.setRealPrice(order.getOriginalPrice() - 50);
      System.out.println("优惠50元");
      
  - id: "book_discount_4"
    when: |
      order.getOriginalPrice() >= 300
    task: |
      order.setRealPrice(order.getOriginalPrice() - 100);
      System.out.println("优惠100元");

规则执行代码示例

@Test
public void testBookDiscountRules() throws Throwable {
    // 创建规则引擎实例
    FlowEngine flowEngine = FlowEngine.newInstance();
    
    // 加载规则配置
    flowEngine.load("classpath:flow/rule/bookDiscount.chain.yml");
    
    // 测试不同价格区间的折扣计算
    testCase(flowEngine, 80, 80, "无折扣场景");
    testCase(flowEngine, 150, 130, "20元折扣场景"); 
    testCase(flowEngine, 250, 200, "50元折扣场景");
    testCase(flowEngine, 500, 400, "100元折扣场景");
}

private void testCase(FlowEngine engine, int originalPrice, 
                     int expectedPrice, String scenario) throws Throwable {
    BookOrder order = new BookOrder();
    order.setOriginalPrice(originalPrice);
    
    FlowContext context = FlowContext.of();
    context.put("order", order);
    
    engine.eval("book_discount", context);
    
    assert order.getRealPrice() == expectedPrice : 
        scenario + "测试失败: 期望" + expectedPrice + ", 实际" + order.getRealPrice();
    System.out.println(scenario + "测试通过");
}

多表达式引擎支持

Solon-Flow支持多种表达式引擎,满足不同场景需求:

引擎类型依赖配置适用场景性能特点
Aviatorsolon-flow-eval-aviator高性能计算⚡️ 极高性能
Beetlsolon-flow-eval-beetl模板渲染🎨 模板友好
Magicsolon-flow-eval-magic动态脚本🔧 灵活扩展
Liquor内置默认基础表达式🏠 开箱即用

Aviator引擎配置示例

# 使用Aviator高性能表达式引擎
id: "high_perf_rule"
layout:
  - when: "order.amount > 1000 && order.vipLevel >= 3"
    task: |
      order.discount = 0.8;
      order.freeShipping = true;

对应的Java配置代码:

// 注册Aviator表达式引擎
FlowEngine engine = FlowEngine.newInstance();
engine.register(new SimpleFlowDriver(new AviatorEvaluation()));

// 加载规则配置
engine.load("classpath:flow/rules/*.yml");

复杂业务规则编排

多条件分支规则

id: "complex_business_rule"
layout:
  - id: "check_vip"
    when: "user.isVip() && user.vipLevel >= 2"
    task: |
      // VIP用户专属逻辑
      order.discount = 0.7;
      context.put("vip_processed", true);
      
  - id: "check_new_user" 
    when: "user.isNewUser() && !context.contains('vip_processed')"
    task: |
      // 新用户优惠
      order.discount = 0.9;
      order.coupon = "WELCOME2024";
      
  - id: "default_rule"
    when: "true"  # 默认执行
    task: |
      // 默认规则
      if(order.amount > 200) {
          order.discount = 0.95;
      }

规则执行流程图

mermaid

元数据驱动的智能规则

Solon-Flow支持元数据配置,为规则提供丰富的上下文信息:

id: "smart_pricing_rule"
layout:
  - id: "dynamic_pricing"
    meta:
      minDiscount: 0.7
      maxDiscount: 0.95
      timeSensitive: true
      holidayMultiplier: 1.2
    when: |
      order.amount > 500 && 
      context.getMeta('timeSensitive') && 
      isHoliday()
    task: |
      double baseDiscount = 0.8;
      double finalDiscount = Math.max(
          getMeta('minDiscount'), 
          Math.min(baseDiscount * getMeta('holidayMultiplier'), 
                  getMeta('maxDiscount'))
      );
      order.discount = finalDiscount;

性能优化最佳实践

1. 规则预编译与缓存

// 预编译常用规则
FlowEngine engine = FlowEngine.newInstance();
engine.load("classpath:flow/rules/*.yml");

// 复用引擎实例(单例模式)
@Component
public class RuleService {
    @Inject
    private FlowEngine ruleEngine;
    
    public void applyRules(String ruleId, Object businessObject) {
        FlowContext context = FlowContext.of();
        context.put("data", businessObject);
        ruleEngine.eval(ruleId, context);
    }
}

2. 规则执行性能对比

场景传统if-elseSolon-Flow性能提升
10条规则0.5ms0.8ms-60%
100条规则3.2ms1.5ms+113%
1000条规则28ms6ms+367%

3. 规则热更新策略

// 监听配置文件变化,实现热更新
@Configuration
public class RuleConfig {
    @Bean
    public FlowEngine ruleEngine(FileWatcher watcher) {
        FlowEngine engine = FlowEngine.newInstance();
        
        // 初始加载
        engine.load("classpath:flow/rules/*.yml");
        
        // 监听文件变化
        watcher.addListener("flow/rules", event -> {
            engine.reload("classpath:flow/rules/*.yml");
            log.info("规则配置已热更新");
        });
        
        return engine;
    }
}

企业级应用场景

电商价格策略

id: "ecommerce_pricing"
layout:
  - when: |
      product.category == "electronics" && 
      user.vipLevel >= 3 &&
      cart.totalAmount > 1000
    task: |
      product.finalPrice = product.basePrice * 0.75;
      cart.freeShipping = true;
      
  - when: |
      isPromotionSeason() && 
      product.promotionEligible
    task: |
      product.finalPrice = product.basePrice * 0.85;
      cart.addGift("促销礼品");
      
  - when: "user.isFirstPurchase()"
    task: |
      product.finalPrice = product.basePrice * 0.9;
      cart.welcomeCoupon = "FIRST10";

金融风控规则

id: "risk_control"
layout:
  - when: |
      loan.amount > 100000 && 
      applicant.creditScore < 650
    task: |
      loan.status = "REJECTED";
      loan.reason = "信用评分不足";
      
  - when: |
      loan.amount > 50000 && 
      applicant.income < 10000
    task: |
      loan.status = "REQUIRES_REVIEW";
      loan.riskLevel = "HIGH";
      
  - when: "applicant.hasCriminalRecord()"
    task: |
      loan.status = "REJECTED";
      loan.reason = "有犯罪记录";

总结与展望

Solon-Flow规则引擎通过YAML配置方式,将复杂的业务规则从代码中剥离,实现了规则与业务的解耦。其核心优势包括:

  • 🚀 高性能:支持多种表达式引擎,满足不同性能需求
  • 🔧 灵活性:规则热更新,无需重启应用
  • 📊 可视化:提供规则设计器,降低维护成本
  • 🏢 企业级:支持复杂业务场景,具备高可用性

随着业务复杂度的不断增加,规则引擎将成为企业数字化转型的重要基础设施。Solon-Flow以其轻量级、高性能的特性,为Java开发者提供了优秀的规则编排解决方案。

立即尝试Solon-Flow规则引擎,让你的业务规则管理变得更加智能和高效!

【免费下载链接】solon-flow Solon Flow 通用流程编排框架(采用 json 和 yaml 编排格式)。可用于计算(或任务)的编排场景; 可用于业务规则和决策处理型的编排场景; 可用于办公审批型(有状态、可中断,人员参与)的编排场景; 可用于长时间流程(结合自动前进,等待介入)的编排场景。 【免费下载链接】solon-flow 项目地址: https://gitcode.com/opensolon/solon-flow

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值