规则引擎由是一种嵌入在应用程序中的组件,实现了将业务决策从应用程序代码中分离出来,并使用预定义的语义模块编写业务决策。接受数据输入,解释业务规则,并根据业务规则做出业务决策。
grule是golang实现的开源规则引擎。

grl

grule有自己的DSL语言来定义规则,GRL,类似Drools(java实现的一款规则引擎)中的DRL。
结构:

rule  <rule_name> <rule_description>
   <attribute> <value> {
   when
      <conditions>

   then
      <actions>
}

实例:

rule SpeedUp "When testcar is speeding up we keep increase the speed." salience 10  {
    when
        TestCar.SpeedUp == true && TestCar.Speed < TestCar.MaxSpeed
    then
        TestCar.Speed = TestCar.Speed + TestCar.SpeedIncrement;
        DistanceRecord.TotalDistance = DistanceRecord.TotalDistance + TestCar.Speed;
}

SpeedUp是规则的名字
"When testcar is speeding up we keep increase the speed." 是规则的描述
salience 10 是规则执行的优先级

实例

一个商品税收分级的例子
2020年前的商品无税 奢侈品15%税率 普通商品10% 税率 其他商品20%税率
GRL如下

rule OnlyCalculatePurchaseInYear2020 "All other purchase dated not in 2020, we should ignore" salience 100 { // 最优先判断非2020未免税
    when
        Purchase.IgnoredPurchase == false && GetTimeYear(Purchase.PurchaseDate) != 2020 && Purchase.PriceAfterTax == 0
    then
        Purchase.IgnoredPurchase = true;
        Retract("OnlyCalculatePurchaseInYear2020");
}

rule TaxingLuxuryItems "When its a luxury Item, you tax them 15 percent." salience 10 {
    when
        Purchase.IgnoredPurchase == false && Purchase.Tax == 0 && Purchase.ItemType == "LUXURY" // 奢侈品税率
    then
        Purchase.Tax = Purchase.Price + (Purchase.Price * 0.15);
}

rule TaxingNormalItems "When its a Normal Item, you tax them 10 percent." salience 8 {
    when
        Purchase.IgnoredPurchase == false && Purchase.Tax == 0 && Purchase.ItemType == "NORMAL"  // 普通税率
    then
        Purchase.Tax = Purchase.Price + (Purchase.Price * 0.1);
}

rule TaxingOtherTypeItems "When its not Normal or Luxury Item, you tax them 20 percent." salience 7 {
    when
        Purchase.IgnoredPurchase == false &&  Purchase.Tax == 0 && Purchase.ItemType != "NORMAL" && Purchase.ItemType != "LUXURY"
    then
        Purchase.Tax = Purchase.Price + (Purchase.Price * 0.2);
}

rule CalculatePriceAfterTax "When tax is calculated, time to calculate price after tax" {
    when
        Purchase.Tax > 0 && Purchase.PriceAfterTax == 0 
    then
        Purchase.PriceAfterTax = Purchase.Price + Purchase.Tax;// 计算税后价格
}

rule SumUpPurchase "When price after tax calculated, sum it up" {
    when
        Purchase.PriceAfterTax > 0
    then
        CashFlow.PurchaseCount = CashFlow.PurchaseCount + 1;
        CashFlow.TotalPurchases = CashFlow.TotalPurchases + Purchase.Price;
        CashFlow.TotalTax = CashFlow.TotalTax + Purchase.Tax;
        CashFlow.PurchasesAfterTax = CashFlow.PurchasesAfterTax + Purchase.PriceAfterTax;
        Retract("SumUpPurchase");
}