规则引擎 - Easy Rules
Easy Rules
- 依赖
- demo
- demo1
- demo2
- 总结
Easy Rules 是一个轻量级的 Java 规则引擎,使用简单,适合快速开发和简单的规则场景,适合对于一些判断,是否属于白名单,是否有特殊权限,是否属于当前区域,调用方法Action 等由前端传入,进行规则处理,其实市面上也有很多规则引擎,但是对比来说,Easy Rules 对于 java 开发来说更加简单和快速,所以可以单开一篇写一下
依赖
<dependency><groupId>org.jeasy</groupId><artifactId>easy-rules-core</artifactId><version>4.4.0</version>
</dependency>
demo
demo1
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import org.jeasy.rules.core.DefaultRulesEngine;
import org.jeasy.rules.core.RuleBuilder;
/*** FileName: FactsExample.java* Author: 寿春* Date: 2025/4/21 19:54* <p>*/
class Person {private String name;private int age;public Person(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public int getAge() {return age;}
}public class FactsExample {public static void main(String[] args) {// 创建 Person 对象Person person = new Person("John", 20);// 使用流式 API 定义规则var ageRule = RuleBuilder.begin().name("Age Rule").description("Check if the person's age is greater than 18").when(facts -> ((Person) facts.get("person")).getAge() > 18).then(facts -> System.out.println(((Person) facts.get("person")).getName() + " is an adult.")).build();// 创建规则集合Rules rules = new Rules();rules.register(ageRule);// 创建事实集合Facts facts = new Facts();// 向事实集合中添加数据facts.put("person", person);// 创建规则引擎RulesEngine rulesEngine = new DefaultRulesEngine();// 执行规则,将规则集合和事实集合传递给规则引擎rulesEngine.fire(rules, facts);}
}
demo2
import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Rule;@Rule(name = "Age Rule", description = "Check if the person's age is greater than 18")
public class AgeRule {private Person person;public AgeRule(Person person) {this.person = person;}@Conditionpublic boolean isAdult() {return person.getAge() > 18;}@Actionpublic void printMessage() {System.out.println(person.getName() + " is an adult.");}
}
/*** FileName: FactsExample.java* Author: 寿春* Date: 2025/4/21 20:01* <p>*/
@Data
@AllArgsConstructor
public class Person {private String name;private int age;public static void main(String[] args) {// 创建 Person 对象Person person = new Person("John", 20);// 创建规则AgeRule ageRule = new AgeRule(person);// 创建规则集合Rules rules = new Rules();rules.register(ageRule);// 创建事实集合Facts facts = new Facts();facts.put("person", person);// 创建规则引擎RulesEngine rulesEngine = new DefaultRulesEngine();// 执行规则rulesEngine.fire(rules, facts);}
}
总结
逻辑很简单
- 创建一个规则, Rules rules = new Rules();
- 需要什么规则 RuleBuilder
- 创建一个事实 Facts facts = new Facts();
- 创建规则引擎 RulesEngine rulesEngine = new DefaultRulesEngine();
- 执行规则 rulesEngine.fire(rules, facts); 这个规则 这个事实