今天看代码的时候,发现了一个好用的规则判断插件,Easy-rule,在判断规则是否满足时,不需要大量的if/else,只需要创建规则和数据,创建引擎执行就可以了。
1、引入插件
<dependency>
<groupId>org.jeasy</groupId>
<artifactId>easy-rules-core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.jeasy</groupId>
<artifactId>easy-rules-support</artifactId>
<version>3.3.0</version>
</dependency>
2、创建规则,常用的有两种方式,一种是注解,一种是Builder构建。可以设置优先级来决定排序关系,值越小优先级越高
@Rule(name = "firstRule" , description = "第一个规则")
public class FirstRule {
@Condition
public boolean even(@Fact("num") Integer num){
return num % 2 == 0;
}
@Action
public void action(@Fact("num") Integer num) {
System.out.printf("%d是偶数",num);
}
@Priority
public int getPriority(){
return 1;
}
}
@Rule(name = "secondRule",description = "第二个规则")
public class SecondRule {
@Condition
public boolean moreThanZero(@Fact("num") Integer num){
return num > 0;
}
@Action
public void action(@Fact("num") Integer num) {
System.out.printf("%d大于0",num);
}
@Priority
public int getPriority(){
return 1;
}
}
还有一种Builder创建
Rule thridRule = new RuleBuilder()
.name("thridRule")
.description("第三个rule")
.when(facts -> (Integer) facts.get("num") % 3 == 0)
.then(facts -> System.out.printf("%d能被3整除",(Integer)facts.get("num")))
.build();
3、创建引擎
3.1、默认引擎,这种引擎没有特殊作用
RulesEngine engine = new DefaultRulesEngine(parameters);
3.2、skipOnFirstAppliedRule,只要有一个匹配的,就不再判断其他条件
// create a rules engine
RulesEngineParameters parameters = new RulesEngineParameters().skipOnFirstAppliedRule(true);
// 创建引擎
RulesEngine engine = new DefaultRulesEngine(parameters);
3.2、skipOnFirstNonTriggeredRule,只要有一个不匹配,就不再判断其他条件,当然不匹配的那一条也不会执行
// create a rules engine
RulesEngineParameters parameters = new RulesEngineParameters().skipOnFirstNonTriggeredRule(true);
// 创建引擎
RulesEngine engine = new DefaultRulesEngine(parameters);
3.3、priorityThreshold(num),只生效优先级的值小于等于num的,其他的不考虑
// create a rules engine
RulesEngineParameters parameters = new RulesEngineParameters().priorityThreshold(1);
// 创建引擎
RulesEngine engine = new DefaultRulesEngine(parameters);
4、执行引擎
// 创建规则
Rules rules = new Rules();
rules.register(new FirstRule());
rules.register(new SecondRule());
rules.register(thridRule);
// 数据
Facts facts = new Facts();
Stream.iterate(0, n -> n + 1)
.limit(10)
.forEach(x -> {
facts.put("num", x);
engine.fire(rules, facts);
System.out.println("\n*****************");
});
网友评论