您好,登錄后才能下訂單哦!
RulesEngine腳本引擎怎么在C#中使用?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。
簡介
RulesEngine是微軟推出的規(guī)則引擎,規(guī)則引擎在很多企業(yè)開發(fā)中有所應(yīng)用,是處理經(jīng)常變動需求的一種優(yōu)雅的方法。個人任務(wù),規(guī)則引擎適用于以下的一些場景:
輸入輸出類型數(shù)量比較固定,但是執(zhí)行邏輯經(jīng)常變化;
switch條件經(jīng)常變化,復(fù)雜switch語句的替代;
會變動的,具有多種條件或者規(guī)則的業(yè)務(wù)邏輯;
規(guī)則自由度不要求特別高的場景。(這種情況建議使用腳本引擎)
RulesEngine的規(guī)則使用JSON進行存儲,通過lambda表達式方式表述規(guī)則(Rules)。
安裝很方便,直接使用nuget進行安裝:
install-pacakge RulesEngine
需要有Rules,有WorkflowName,然后還有一些屬性。
[ { "WorkflowName": "Discount", "Rules": [ { "RuleName": "GiveDiscount10", "SuccessEvent": "10", "ErrorMessage": "One or more adjust rules failed.", "ErrorType": "Error", "RuleExpressionType": "LambdaExpression", "Expression": "input1.country == \"india\" AND input1.loyalityFactor <= 2 AND input1.totalPurchasesToDate >= 5000 AND input2.totalOrders > 2 AND input3.noOfVisitsPerMonth > 2" } ] } ]
除了標(biāo)準(zhǔn)的RuleExpressionType
,還可以通過定義Rules嵌套多個條件,下面是Or邏輯。
{ "RuleName": "GiveDiscount30NestedOrExample", "SuccessEvent": "30", "ErrorMessage": "One or more adjust rules failed.", "ErrorType": "Error", "Operator": "OrElse", "Rules":[ { "RuleName": "IsLoyalAndHasGoodSpend", "ErrorMessage": "One or more adjust rules failed.", "ErrorType": "Error", "RuleExpressionType": "LambdaExpression", "Expression": "input1.loyalityFactor > 3 AND input1.totalPurchasesToDate >= 50000 AND input1.totalPurchasesToDate <= 100000" }, { "RuleName": "OrHasHighNumberOfTotalOrders", "ErrorMessage": "One or more adjust rules failed.", "ErrorType": "Error", "RuleExpressionType": "LambdaExpression", "Expression": "input2.totalOrders > 15" } ] }
可以從官方的代碼庫中下載示例,定義了上述規(guī)則,就可以直接開始用了。示例描述了這么一個應(yīng)用場景:
根據(jù)不同的客戶屬性,提供不同的折扣。由于銷售的情況變化較快,提供折扣的規(guī)則也需要經(jīng)常變動。因此比較適用于規(guī)則引擎。
public void Run() { Console.WriteLine($"Running {nameof(BasicDemo)}...."); //創(chuàng)建輸入 var basicInfo = "{\"name\": \"hello\",\"email\": \"abcy@xyz.com\",\"creditHistory\": \"good\",\"country\": \"canada\",\"loyalityFactor\": 3,\"totalPurchasesToDate\": 10000}"; var orderInfo = "{\"totalOrders\": 5,\"recurringItems\": 2}"; var telemetryInfo = "{\"noOfVisitsPerMonth\": 10,\"percentageOfBuyingToVisit\": 15}"; var converter = new ExpandoObjectConverter(); dynamic input1 = JsonConvert.DeserializeObject<ExpandoObject>(basicInfo, converter); dynamic input2 = JsonConvert.DeserializeObject<ExpandoObject>(orderInfo, converter); dynamic input3 = JsonConvert.DeserializeObject<ExpandoObject>(telemetryInfo, converter); var inputs = new dynamic[] { input1, input2, input3 }; //加載規(guī)則 var files = Directory.GetFiles(Directory.GetCurrentDirectory(), "Discount.json", SearchOption.AllDirectories); if (files == null || files.Length == 0) throw new Exception("Rules not found."); var fileData = File.ReadAllText(files[0]); var workflowRules = JsonConvert.DeserializeObject<List<WorkflowRules>>(fileData); //初始化規(guī)則引擎 var bre = new RulesEngine.RulesEngine(workflowRules.ToArray(), null); string discountOffered = "No discount offered."; //執(zhí)行規(guī)則 List<RuleResultTree> resultList = bre.ExecuteAllRulesAsync("Discount", inputs).Result; //處理結(jié)果 resultList.OnSuccess((eventName) => { discountOffered = $"Discount offered is {eventName} % over MRP."; }); resultList.OnFail(() => { discountOffered = "The user is not eligible for any discount."; }); Console.WriteLine(discountOffered); }
輸入一般來說是IEnumerable<dynamic>
或者是匿名類型,上面實例展示的是由json反序列化形成的dynamic類型,對于程序生成的數(shù)據(jù),使用匿名類型更加方便。
var nestedInput = new { SimpleProp = "simpleProp", NestedProp = new { SimpleProp = "nestedSimpleProp", ListProp = new List<ListItem> { new ListItem { Id = 1, Value = "first" }, new ListItem { Id = 2, Value = "second" } } } };
和腳本引擎一樣,默認規(guī)則引擎只能訪問System的命名空間。如果需要使用到稍微復(fù)雜一些的類型,可以自己定義類型或者函數(shù)。比如定義一個這樣的函數(shù):
public static class Utils { public static bool CheckContains(string check, string valList) { if (String.IsNullOrEmpty(check) || String.IsNullOrEmpty(valList)) return false; var list = valList.Split(',').ToList(); return list.Contains(check); } }
需要使用的時候,先將類傳遞給RulesEngine:
var reSettingsWithCustomTypes = new ReSettings { CustomTypes = new Type[] { typeof(Utils) } }; var engine = new RulesEngine.RulesEngine(workflowRules.ToArray(), null, reSettingsWithCustomTypes);
然后就可以直接在表達式中使用了。
"Expression": "Utils.CheckContains(input1.country, \"india,usa,canada,France\") == true"
默認情況下,規(guī)則的輸入使用的是類似input1 input2這樣的形式,如果想直觀一點,可以使用RuleParameter來進行封裝具體的參數(shù)類型。
RuleParameter ruleParameter = new RuleParameter("NIP", nestedInput); var resultList = bre.ExecuteAllRulesAsync(workflow.WorkflowName, ruleParameter).Result;
如果表達式比較復(fù)雜的情況下,可以使用本地變量來進行分段處理,這對調(diào)試來說會比較方便。
本地變量的關(guān)鍵字為localParams,可以將中間的內(nèi)容簡單理解成var name = expression
{ "name": "allow_access_if_all_mandatory_trainings_are_done_or_access_isSecure", "errorMessage": "Please complete all your training(s) to get access to this content or access it from a secure domain/location.", "errorType": "Error", "localParams": [ { "name": "completedSecurityTrainings", "expression": "MasterSecurityComplainceTrainings.Where(Status.Equals(\"Completed\", StringComparison.InvariantCultureIgnoreCase))" }, { "name": "completedProjectTrainings", "expression": "MasterProjectComplainceTrainings.Where(Status.Equals(\"Completed\", StringComparison.InvariantCultureIgnoreCase))" }, { "name": "isRequestAccessSecured", "expression": "UserRequestDetails.Location.Country == \"India\" ? ((UserRequestDetails.Location.City == \"Bangalore\" && UserRequestDetails.Domain=\"xxxx\")? true : false):false" } ], "expression": "(completedSecurityTrainings.Any() && completedProjectTrainings.Any()) || isRequestAccessSecured " }
看完上述內(nèi)容,你們掌握RulesEngine腳本引擎怎么在C#中使用的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。