Easy-Rule是一个轻量级的规则引擎,也非常容易上手。有了它,“满100减30,满200减60,最高减免xxx”, 程序员就不会因为规则实现错误公司被薅羊毛而被拉去祭天了。
###规则定义
以下是一个官方提供的Helloworld案例。
```
package org.jeasy.rules.tutorials.helloworld;
import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Rule;
@Rule(name = "Hello World rule", description = "Always say hello world")
public class HelloWorldRule {
@Condition
public boolean when() {
return true;
}
@Action
public void then() {
System.out.println("hello world");
}
}
````
Easy-rule通过@Rule注解来定义规则
@Conition注解的方法来表示条件桩。
@Action方法来表示动作桩。
在一个Rule中,只有当条件桩方法返回值为true时,动作桩方法才会被调用。
Rule注解name、description和priority三个属性。如果有多个规则的话,要保证name的唯一性,另外priority也决定了规则执行的优先顺序。
````
package org.jeasy.rules.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Rule {
String name() default "rule";
String description() default "description";
int priority() default 2147483646;
}
````
###规则执行
```
package org.jeasy.rules.tutorials.helloworld;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import org.jeasy.rules.core.DefaultRulesEngine;
public class Launcher {
public static void main(String[] args) {
// create facts
Facts facts = new Facts();
// create rules
Rules rules = new Rules();
rules.register(new HelloWorldRule());
// create a rules engine and fire rules on known facts
RulesEngine rulesEngine = new DefaultRulesEngine();
rulesEngine.fire(rules, facts);
}
}
```
在调用者中,首先定义了规则集Rules,以及Facts这样一个参数map,最后再创建RuleEngine,并调用fire方法,传入rules和facts。
规则引擎会按照优先级逐个调用注册的规则。
后续介绍
-规则引擎停止执行的几种方式:如遇到第一个条件符合/不符合就停止?
-组合规则: 应对规则嵌套等复杂业务需求
-一个规则多动作桩
-Spring整合
最后来看一下实战。阿里也有开源的规则引擎,感兴趣的同学可以翻翻github。
