加载不通的规则引擎配置文件,使用DynamicExpresso校验采集数据,得出是否告警
rules.json
{ "Rules": [ { "Description": "温度超过阈值警报", "Condition": "temperature > 30", "Action": "HT" }, { "Description": "湿度低于阈值警报", "Condition": "humidity < 20", "Action": "LH" }, { "Description": "温度和湿度都正常", "Condition": "temperature <= 30 AND humidity >= 20", "Action": "THN" } ] }
RuleMgr.cs
using DynamicExpresso; using System.Text.Json; namespace ConfigRules { // 用于存储来自 JSON 文件的规则 public class Rule { public string Description { get; set; } public string Condition { get; set; } public string Action { get; set; } } public class RuleSet { public List<Rule> Rules { get; set; } } public class RuleMgr { static List<Rule> rules; public static void LoadConfig(string filePath) { try { var jsonString = File.ReadAllText(filePath); var ruleSet = JsonSerializer.Deserialize<RuleSet>(jsonString); rules = ruleSet?.Rules ?? new List<Rule>(); } catch (Exception ex) { Console.WriteLine($"[Error] RuleMgr,LoadConfig,errmsg:{ex.Message}"); } } public static void CompileCondition(Dictionary<string, double> datas) { try { var lstParam = new List<Parameter>(); foreach (var data in datas) { lstParam.Add(new Parameter(data.Key, data.Value));// 将传感器数据填入表达式的参数 } // 评估规则 var interpreter = new Interpreter(); foreach (var rule in rules) { var condition = rule.Condition.Replace(" AND ", " && ").Replace(" OR ", " || "); bool result = (bool)interpreter.Eval(condition, lstParam.ToArray()); if (result) { Console.WriteLine(rule.Description); switch (rule.Action) { case "HT": break; case "LH": break; case "THN": break; } } } } catch (Exception ex) { Console.WriteLine($"[Error] RuleMgr,CompileCondition,errmsg:{ex.Message}"); } } } }
Program.cs
namespace ConfigRules { internal class Program { static void Main(string[] args) { // 模拟传感器数据 var sensorData = new Dictionary<string, double> { { "temperature", 50 }, { "humidity", 10 } }; // 读取 JSON 文件中的规则 RuleMgr.LoadConfig("rules.json"); RuleMgr.CompileCondition(sensorData); Console.ReadLine(); } } }