文章目录
前言
最近,公司有个项目,需要根据不同的规则来检验是否满足条件,由于条件可以配置,所以需要在开发的时候考虑条件的可拓展性,不能因为新增了规则,就需要修改规则,所以决定在使用规则引擎来处理条件校验。
一、easy-rule简介
Easy Rules是一个简单而强大的Java规则引擎,具有轻量级框架和易于学习的API,基于POJO的开发与注解的编程模型,定义抽象的业务规则并轻松应用它们,支持从简单规则创建组合规则的能力,支持使用表达式语言(如MVEL和SpEL)定义规则的能力。
正是因为Easy Rule的简单轻量级,不需要引入额外的资源,此外是Java技术栈,方便学习等因素,所以才选择Easy Rule。Easy Rule中使用MVEL进行表达式解析,详细用法见 Mvel2.0使用指南一 基础
二、使用步骤
Easy Rule的使用方法,可以参考Github
1.引入库
<!-- easy rules核心库 -->
<dependency>
<groupId>org.jeasy</groupId>
<artifactId>easy-rules-core</artifactId>
<version>4.1.0</version>
</dependency>
<!-- 规定定义文件格式,支持json,yaml等 -->
<dependency>
<groupId>org.jeasy</groupId>
<artifactId>easy-rules-support</artifactId>
<version>4.1.0</version>
</dependency>
<!-- 支持mvel规则语法库 -->
<dependency>
<groupId>org.jeasy</groupId>
<artifactId>easy-rules-mvel</artifactId>
<version>4.1.0</version>
</dependency>
2.定义规则
2.1 使用声明式方式
@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!");
}
}
2.2 使用流程API的方式
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();
2.3 使用表达式
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();
2.4 使用配置文件
name: "weather rule"
description: "if it rains then take an umbrella"
condition: "rain == true"
actions:
- "System.out.println(\"It rains, take an umbrella!\");"
MVELRuleFactory ruleFactory = new MVELRuleFactory(new YamlRuleDefinitionReader());
Rule weatherRule = ruleFactory.createRule(new FileReader("weather-rule.yml"));
3. 触发规则
public class Test {
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);
}
}
项目demo
由于公司项目条件是有分组的概念,一个分组内的条件是且的关系,多个分组之间的条件是或的关系,而且只需要校验条件是否成立即可,所以和上面的使用步骤还是有点区别。我本地测试的demo如下:
1 校验对象定义
@Data
public class Person {
/**
* 年龄
*/
private int age;
/**
* 姓名
*/
private String name;
/**
* 是否成年
*/
private boolean adult;
/**
* 性别,1:男,2:女,0:未知
*/
private int sex;
/**
* 身高,单位:cm
*/
private int height;
}
2. 多个分组条件定义
先采用yml文件配置的方式,name 相同则为同一个分组。
---
name: "rule1"
description: "nameRule"
priority: 1
condition: "person.name == '张三'"
actions:
- "System.out.println(\"success!!!\");"
---
name: "rule1"
description: "ageRule"
priority: 2
condition: "person.age > 18"
actions:
- "person.setAdult(true);"
---
name: "rule2"
description: "sexRule"
priority: 1
condition: "person.sex == 1"
actions:
- "System.out.println(\"I am a boy!!!\");"
---
name: "rule3"
description: "heightRule"
priority: 1
condition: "person.height > 170"
actions:
- "System.out.println(\"I am a boy!!!\");"
3. 测试用例
public static void main(String[] args) throws Exception {
MVELRuleFactory ruleFactory = new MVELRuleFactory(new YamlRuleDefinitionReader());
Rules rules = ruleFactory.createRules(new FileReader("E:\\Java\\workspace\\spring-demo\\easy-rule-test\\src\\main\\resources\\testRule.yml"));
Person person = new Person();
person.setAge(19);
person.setName("张三");
person.setSex(1);
person.setHeight(180);
Facts facts = new Facts();
facts.put("person", person);
RulesEngine rulesEngine = new DefaultRulesEngine();
Map<Rule, Boolean> result = rulesEngine.check(rules, facts);
System.out.println("检测对象:" + person);
System.out.println("检测结果:" + result);
person.setAge(17);
person.setSex(2);
person.setHeight(166);
result = rulesEngine.check(rules, facts);
System.out.println("检测对象:" + person);
System.out.println("检测结果:" + result);
}
检验结果:
13:41:57.199 [main] DEBUG org.jeasy.rules.core.DefaultRulesEngine - Checking rules
检测对象:Person(age=19, name=张三, adult=false, sex=1, height=180)
检测结果:{rule1=true, rule3=true, rule1=true, rule2=true}
13:41:57.230 [main] DEBUG org.jeasy.rules.core.DefaultRulesEngine - Checking rules
检测对象:Person(age=17, name=张三, adult=false, sex=2, height=166)
检测结果:{rule1=false, rule3=false, rule1=true, rule2=false}
从返回的结果,rule1的结果返回了两个,不符合当前的需求,所以进行调整了一下,如下所示:
4. 调整后的DEMO
public static void main(String[] args) throws Exception {
MVELRuleFactory ruleFactory = new MVELRuleFactory(new YamlRuleDefinitionReader());
Rules rules = ruleFactory.createRules(new FileReader("E:\\Java\\workspace\\spring-demo\\easy-rule-test\\src\\main\\resources\\testRule.yml"));
Person person = new Person();
person.setAge(19);
person.setName("张三");
person.setSex(1);
person.setHeight(180);
Facts facts = new Facts();
facts.put("person", person);
RulesEngine rulesEngine = new DefaultRulesEngine();
Map<String, Boolean> result = groupCheck(rules, facts);
System.out.println("检测对象:" + person);
System.out.println("检测结果:" + result);
person.setAge(17);
person.setSex(2);
person.setHeight(166);
result = groupCheck(rules, facts);
System.out.println("检测对象:" + person);
System.out.println("检测结果:" + result);
}
public static Map<String, List<Rule>> convertGroupRule(Rules rules){
Map<String, List<Rule>> ruleMap = new HashMap<>();
for (Rule rule : rules) {
List<Rule> ruleList = ruleMap.getOrDefault(rule.getName(), new ArrayList<>());
ruleList.add(rule);
ruleMap.put(rule.getName(), ruleList);
}
return ruleMap;
}
public static Map<String, Boolean> groupCheck(Rules rules, Facts facts){
Map<String, Boolean> result = new HashMap<>();
Map<String, List<Rule>> ruleMap = convertGroupRule(rules);
for (Map.Entry<String, List<Rule>> entry : ruleMap.entrySet()){
List<Rule> ruleList = entry.getValue();
Boolean ok = null;
for (Rule rule: ruleList){
if (!rule.evaluate(facts)){
ok = Boolean.FALSE;
break;
} else {
ok = Boolean.TRUE;
}
}
result.put(entry.getKey(), ok);
}
return result;
}
检测对象:Person(age=19, name=张三, adult=false, sex=1, height=180)
检测结果:{rule1=true, rule3=true, rule2=true}
检测对象:Person(age=17, name=张三, adult=false, sex=2, height=166)
检测结果:{rule1=false, rule3=false, rule2=false}