easy-rules小試牛刀

本文主要研究下easy-rules。

easy-rules是一款輕量級的規(guī)則引擎。

maven

        <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>

Rule創(chuàng)建方式

基于mvel表達(dá)式

easy-rules首先集成了mvel表達(dá)式捂襟,后續(xù)可能集成SpEL

  • 配置文件
name: "alcohol rule"
description: "children are not allowed to buy alcohol"
priority: 2
condition: "person.isAdult() == false"
actions:
  - "System.out.println(\"Shop: Sorry, you are not allowed to buy alcohol\");"
  • 加載運(yùn)行
        //create a person instance (fact)
        Person tom = new Person("Tom", 14);
        Facts facts = new Facts();
        facts.put("person", tom);

        MVELRule alcoholRule = MVELRuleFactory.createRuleFrom(new File(getClass().getClassLoader().getResource("alcohol-rule.yml").getFile()));

        // create a rule set
        Rules rules = new Rules();
        rules.register(alcoholRule);

        //create a default rules engine and fire rules on known facts
        RulesEngine rulesEngine = new DefaultRulesEngine();

        System.out.println("Tom: Hi! can I have some Vodka please?");
        rulesEngine.fire(rules, facts);

注解方式

@Rule
public class BuzzRule {

    @Condition
    public boolean isBuzz(@Fact("number") Integer number) {
        return number % 7 == 0;
    }

    @Action
    public void printBuzz() {
        System.out.println("buzz");
    }

    @Priority
    public int getPriority() {
        return 2;
    }
}
  • @Rule可以標(biāo)注name和description屬性暖呕,每個rule的name要唯一哲泊,如果沒有指定堪侯,則RuleProxy則默認(rèn)取類名
  • @Condition是條件判斷埃碱,要求返回boolean值猖辫,表示是否滿足條件
  • @Action標(biāo)注條件成立之后觸發(fā)的方法
  • @Priority標(biāo)注該rule的優(yōu)先級,默認(rèn)是Integer.MAX_VALUE - 1砚殿,值越小越優(yōu)先

實(shí)現(xiàn)Rule接口

easy-rules-core-3.1.0-sources.jar!/org/jeasy/rules/api/Rule.java

/**
 * Abstraction for a rule that can be fired by the rules engine.
 *
 * Rules are registered in a rule set of type <code>Rules</code> in which they must have a <strong>unique</strong> name.
 *
 * @author Mahmoud Ben Hassine (mahmoud.benhassine@icloud.com)
 */
public interface Rule extends Comparable<Rule> {

    /**
     * Default rule name.
     */
    String DEFAULT_NAME = "rule";

    /**
     * Default rule description.
     */
    String DEFAULT_DESCRIPTION = "description";

    /**
     * Default rule priority.
     */
    int DEFAULT_PRIORITY = Integer.MAX_VALUE - 1;

    /**
     * Getter for rule name.
     * @return the rule name
     */
    String getName();

    /**
     * Getter for rule description.
     * @return rule description
     */
    String getDescription();

    /**
     * Getter for rule priority.
     * @return rule priority
     */
    int getPriority();

    /**
     * Rule conditions abstraction : this method encapsulates the rule's conditions.
     * <strong>Implementations should handle any runtime exception and return true/false accordingly</strong>
     *
     * @return true if the rule should be applied given the provided facts, false otherwise
     */
    boolean evaluate(Facts facts);

    /**
     * Rule actions abstraction : this method encapsulates the rule's actions.
     * @throws Exception thrown if an exception occurs during actions performing
     */
    void execute(Facts facts) throws Exception;

}

實(shí)現(xiàn)這個接口啃憎,也是創(chuàng)建rule的一種形式。

源碼解析

  • register
    easy-rules-core-3.1.0-sources.jar!/org/jeasy/rules/api/Rules.java
    /**
     * Register a new rule.
     *
     * @param rule to register
     */
    public void register(Object rule) {
        Objects.requireNonNull(rule);
        rules.add(RuleProxy.asRule(rule));
    }

這里使用RuleProxy.asRule方法

  • RuleProxy
    easy-rules-core-3.1.0-sources.jar!/org/jeasy/rules/core/RuleProxy.java
    /**
     * Makes the rule object implement the {@link Rule} interface.
     *
     * @param rule the annotated rule object.
     * @return a proxy that implements the {@link Rule} interface.
     */
    public static Rule asRule(final Object rule) {
        Rule result;
        if (rule instanceof Rule) {
            result = (Rule) rule;
        } else {
            ruleDefinitionValidator.validateRuleDefinition(rule);
            result = (Rule) Proxy.newProxyInstance(
                    Rule.class.getClassLoader(),
                    new Class[]{Rule.class, Comparable.class},
                    new RuleProxy(rule));
        }
        return result;
    }

可以看到似炎,如果有實(shí)現(xiàn)Rule接口辛萍,則直接返回,沒有的話(即基于注解的形式)羡藐,則利用JDK的動態(tài)代理進(jìn)行包裝贩毕。

  • invoke
   @Override
    public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
        String methodName = method.getName();
        switch (methodName) {
            case "getName":
                return getRuleName();
            case "getDescription":
                return getRuleDescription();
            case "getPriority":
                return getRulePriority();
            case "compareTo":
                return compareToMethod(args);
            case "evaluate":
                return evaluateMethod(args);
            case "execute":
                return executeMethod(args);
            case "equals":
                return equalsMethod(args);
            case "hashCode":
                return hashCodeMethod();
            case "toString":
                return toStringMethod();
            default:
                return null;
        }
    }

可以看到這里invoke對方法進(jìn)行了適配

下面以getName為例看下如何根據(jù)注解來返回

    private String getRuleName() {
        org.jeasy.rules.annotation.Rule rule = getRuleAnnotation();
        return rule.name().equals(Rule.DEFAULT_NAME) ? getTargetClass().getSimpleName() : rule.name();
    }

可以看到這里對注解進(jìn)行了解析

小結(jié)

從本質(zhì)上看,規(guī)則引擎的目的就是要以松散靈活的方式來替代硬編碼式的if else判斷仆嗦,來達(dá)到解耦的目的辉阶,不過實(shí)際場景要額外注意規(guī)則表達(dá)式的安全問題。

doc

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末欧啤,一起剝皮案震驚了整個濱河市睛藻,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌邢隧,老刑警劉巖店印,帶你破解...
    沈念sama閱讀 222,183評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異倒慧,居然都是意外死亡按摘,警方通過查閱死者的電腦和手機(jī)包券,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來炫贤,“玉大人溅固,你說我怎么就攤上這事±颊洌” “怎么了侍郭?”我有些...
    開封第一講書人閱讀 168,766評論 0 361
  • 文/不壞的土叔 我叫張陵,是天一觀的道長掠河。 經(jīng)常有香客問我亮元,道長,這世上最難降的妖魔是什么唠摹? 我笑而不...
    開封第一講書人閱讀 59,854評論 1 299
  • 正文 為了忘掉前任爆捞,我火速辦了婚禮,結(jié)果婚禮上勾拉,老公的妹妹穿的比我還像新娘煮甥。我一直安慰自己,他們只是感情好藕赞,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,871評論 6 398
  • 文/花漫 我一把揭開白布成肘。 她就那樣靜靜地躺著,像睡著了一般找默。 火紅的嫁衣襯著肌膚如雪艇劫。 梳的紋絲不亂的頭發(fā)上吼驶,一...
    開封第一講書人閱讀 52,457評論 1 311
  • 那天惩激,我揣著相機(jī)與錄音,去河邊找鬼蟹演。 笑死风钻,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的酒请。 我是一名探鬼主播骡技,決...
    沈念sama閱讀 40,999評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼羞反!你這毒婦竟也來了布朦?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,914評論 0 277
  • 序言:老撾萬榮一對情侶失蹤昼窗,失蹤者是張志新(化名)和其女友劉穎是趴,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體澄惊,經(jīng)...
    沈念sama閱讀 46,465評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡唆途,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,543評論 3 342
  • 正文 我和宋清朗相戀三年富雅,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片肛搬。...
    茶點(diǎn)故事閱讀 40,675評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡没佑,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出温赔,到底是詐尸還是另有隱情蛤奢,我是刑警寧澤,帶...
    沈念sama閱讀 36,354評論 5 351
  • 正文 年R本政府宣布陶贼,位于F島的核電站远剩,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏骇窍。R本人自食惡果不足惜瓜晤,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,029評論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望腹纳。 院中可真熱鬧痢掠,春花似錦、人聲如沸嘲恍。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽佃牛。三九已至淹辞,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間俘侠,已是汗流浹背象缀。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留爷速,地道東北人央星。 一個月前我還...
    沈念sama閱讀 49,091評論 3 378
  • 正文 我出身青樓,卻偏偏與公主長得像惫东,于是被迫代替她去往敵國和親莉给。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,685評論 2 360

推薦閱讀更多精彩內(nèi)容