寫了個簡單的規則引擎,普通情況夠用了:
比如2家公司有各自的利率計算規則,如下:
在C#方面,沒有寫在C#的業務邏輯代碼中,而是移到了外部規則文件中,如(ACompanyRatePolicy.r):
rule "Level 1" when alreadyCostPrice >= 0 alreadyCostPrice < 100 then rate = 1 end rule "Level 2" when alreadyCostPrice >= 100 alreadyCostPrice < 300 then rate = 0.8 end rule "Level 3" when alreadyCostPrice >= 300 then rate = 0.5 end
不同的公司調用不同的Policy定義文件來執行邏輯:
核心調用代碼:
public class CustomerRateService { public static decimal CalculateRate(decimal costedAlready, decimal priceThisTime, string rulePolicy) { using (RuleEngine engine = new RuleEngine(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Rules"))) { engine.BindRule("Rating", rulePolicy); //此處的第一個參數"Rating"是規則組名稱,對應的是物理文件夾,方便規則文件的管理和查看 engine.SetParameter("alreadyCostPrice", costedAlready); engine.SetParameter("thisTimePrice", priceThisTime); engine.Process(); return engine.GetDecimal("rate"); } } }
原理比較簡單:
- 根據規則文件(.r文件)生成js代碼
- 在C#中嵌入v8引擎執行這段js代碼
- 獲取結果
代碼已經更新到A2D Framework了。
大家拿去用吧。。。哈哈。