规则引擎-easy rules
easy rules
easy rules is a Java rules engine inspired by an article called “Should I use a Rules Engine?” of Martin Fowler in which Martin says:
You can build a simple rules engine yourself. All you need is to create a bunch of objects with conditions and actions, store them in a collection, and run through them to evaluate the conditions and execute the actions.
这正是Easy Rules所做的,它提供Rule抽象以创建具有条件和动作的规则,并提供RuleEngine API,该API通过一组规则运行以评估条件并执行动作。
核心特性
- 轻量级库和易于学习的API
- 基于POJO的开发与注释编程模型
- 有用的抽象定义业务规则并通过Java轻松应用
- 从原始规则创建复合规则的能力
- 使用表达式语言(如MVEL和SpEL)定义规则的能力
ps: 个人感觉比如 drools,这个设计更加符合我的口味。
快速入门
maven 引入
[xml]
<dependency> <groupId>org.jeasy</groupId> <artifactId>easy-rules-core</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>org.jeasy</groupId> <artifactId>easy-rules-mvel</artifactId> <version>3.1.0</version> </dependency>
定义你的规则
注解式
[java]
@Rule(name = "weather rule", description = "if it rains then take an umbrella" ) public class WeatherRule { @Condition public boolean itRains(@Fact("rain") boolean rain) { return rain; } @Action public void takeAnUmbrella() { System.out.println("It rains, take an umbrella!"); } }
声明式
[java]
Rule weatherRule = new RuleBuilder() .name("weather rule") .description("if it rains then take an umbrella") .when(facts -> facts.get("rain").equals(true)) .then(facts -> System.out.println("It rains, take an umbrella!")) .build();
使用 EL 表达式
[java]
Rule weatherRule = new MVELRule() .name("weather rule") .description("if it rains then take an umbrella") .when("rain == true") .then("System.out.println(\"It rains, take an umbrella!\");");
使用规则描述符
类似于 weather-rule.yml
的写法: [yml]
name: "weather rule" description: "if it rains then take an umbrella" condition: "rain == true" actions: - "System.out.println(\"It rains, take an umbrella!\");"
- 使用
[java]
MVELRuleFactory ruleFactory = new MVELRuleFactory(new YamlRuleDefinitionReader()); Rule weatherRule = ruleFactory.createRule(new FileReader("weather-rule.yml"));
触发
[java]
public static void main(String[] args) { // define facts Facts facts = new Facts(); facts.put("rain", true); // define rules Rule weatherRule = ... Rules rules = new Rules(); rules.register(weatherRule); // fire rules on known facts RulesEngine rulesEngine = new DefaultRulesEngine(); rulesEngine.fire(rules, facts); }
原文链接:https://houbb.github.io/2020/05/26/rule-engine-02-easy-rules
关注公众号:程序新视界,一个让你软实力、硬技术同步提升的平台
除非注明,否则均为程序新视界原创文章,转载必须以链接形式标明本文链接