Java规则引擎Easy Rules的使用介绍
1. easy rules 概述
easy rules是一个java规则引擎,灵感来自一篇名为《should i use a rules engine?》的文章
规则引擎就是提供一种可选的计算模型。与通常的命令式模型(由带有条件和循环的命令依次组成)不同,规则引擎基于生产规则系统。这是一组生产规则,每条规则都有一个条件(condition)和一个动作(action)———— 简单地说,可以将其看作是一组if-then语句。
精妙之处在于规则可以按任何顺序编写,引擎会决定何时使用对顺序有意义的任何方式来计算它们。考虑它的一个好方法是系统运行所有规则,选择条件成立的规则,然后执行相应的操作。这样做的好处是,很多问题都很自然地符合这个模型:
if car.owner.hascellphone then premium += 100;
if car.model.theftrating > 4 then premium += 200;
if car.owner.livesindodgyarea && car.model.theftrating > 2 then premium += 300;
规则引擎是一种工具,它使得这种计算模型编程变得更容易。它可能是一个完整的开发环境,或者一个可以在传统平台上工作的框架。生产规则计算模型最适合仅解决一部分计算问题,因此规则引擎可以更好地嵌入到较大的系统中。
你可以自己构建一个简单的规则引擎。你所需要做的就是创建一组带有条件和动作的对象,将它们存储在一个集合中,然后遍历它们以评估条件并执行这些动作。
easy rules它提供rule抽象以创建具有条件和动作的规则,并提供ruleengine api,该api通过一组规则运行以评估条件并执行动作。
easy rules简单易用,只需两步:
首先,定义规则,方式有很多种
方式一:注解
@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!"); } }
方式二:链式编程
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();
方式三:表达式
rule weatherrule = new mvelrule() .name("weather rule") .description("if it rains then take an umbrella") .when("rain == true") .then("system.out.println(\"it rains, take an umbrella!\");");
方式四:yml配置文件
例如:weather-rule.yml
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"));
接下来,应用规则
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); } }
入门案例:hello easy rules
<dependency> <groupid>org.jeasy</groupid> <artifactid>easy-rules-core</artifactid> <version>4.0.0</version> </dependency>
通过骨架创建maven项目:
mvn archetype:generate \ -darchetypegroupid=org.jeasy \ -darchetypeartifactid=easy-rules-archetype \ -darchetypeversion=4.0.0
默认给我们生成了一个helloworldrule规则,如下:
package com.cjs.example.rules; 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() throws exception { system.out.println("hello world"); } }
2. 规则定义
2.1. 定义规则
大多数业务规则可以用以下定义表示:
- name : 一个命名空间下的唯一的规则名称
- description : 规则的简要描述
- priority : 相对于其他规则的优先级
- facts : 事实,可立即为要处理的数据
- conditions : 为了应用规则而必须满足的一组条件
- actions : 当条件满足时执行的一组动作
easy rules为每个关键点提供了一个抽象来定义业务规则。
在easy rules中,rule接口代表规则
public interface rule { /** * this method encapsulates the rule's conditions. * @return true if the rule should be applied given the provided facts, false otherwise */ boolean evaluate(facts facts); /** * this method encapsulates the rule's actions. * @throws exception if an error occurs during actions performing */ void execute(facts facts) throws exception; //getters and setters for rule name, description and priority omitted. }
evaluate方法封装了必须计算结果为true才能触发规则的条件。execute方法封装了在满足规则条件时应该执行的动作。条件和操作由condition和action接口表示。
定义规则有两种方式:
- 通过在pojo类上添加注解
- 通过rulebuilder api编程
可以在一个pojo类上添加@rule注解,例如:
@rule(name = "my rule", description = "my rule description", priority = 1) public class myrule { @condition public boolean when(@fact("fact") fact) { //my rule conditions return true; } @action(order = 1) public void then(facts facts) throws exception { //my actions } @action(order = 2) public void finally() throws exception { //my final actions } }
@condition注解指定规则条件
@fact注解指定参数
@action注解指定规则执行的动作
rulebuilder支持链式风格定义规则,例如:
rule rule = new rulebuilder() .name("myrule") .description("myruledescription") .priority(3) .when(condition) .then(action1) .then(action2) .build();
组合规则
compositerule由一组规则组成。这是一个典型地组合设计模式的实现。
组合规则是一个抽象概念,因为可以以不同方式触发组合规则。
easy rules自带三种compositerule实现:
- unitrulegroup : 要么应用所有规则,要么不应用任何规则(and逻辑)
- activationrulegroup : 它触发第一个适用规则,并忽略组中的其他规则(xor逻辑)
- conditionalrulegroup : 如果具有最高优先级的规则计算结果为true,则触发其余规则
复合规则可以从基本规则创建并注册为常规规则:
//create a composite rule from two primitive rules unitrulegroup myunitrulegroup = new unitrulegroup("myunitrulegroup", "unit of myrule1 and myrule2"); myunitrulegroup.addrule(myrule1); myunitrulegroup.addrule(myrule2); //register the composite rule as a regular rule rules rules = new rules(); rules.register(myunitrulegroup); rulesengine rulesengine = new defaultrulesengine(); rulesengine.fire(rules, somefacts);
每个规则都有优先级。它代表触发注册规则的默认顺序。默认情况下,较低的值表示较高的优先级。可以重写compareto方法以提供自定义优先级策略。
2.2. 定义事实
在easy rules中,fact api代表事实
public class fact<t> { private final string name; private final t value; }
举个栗子:
fact<string> fact = new fact("foo", "bar"); facts facts = new facts(); facts.add(fact);
或者,也可以用这样简写形式
facts facts = new facts(); facts.put("foo", "bar");
用@fact注解可以将facts注入到condition和action方法中
@rule class weatherrule { @condition public boolean itrains(@fact("rain") boolean rain) { return rain; } @action public void takeanumbrella(facts facts) { system.out.println("it rains, take an umbrella!"); // can add/remove/modify facts } }
2.3. 定义规则引擎
easy rules提供两种rulesengine接口实现:
- defaultrulesengine : 根据规则的自然顺序应用规则
- inferencerulesengine : 持续对已知事实应用规则,直到不再适用任何规则为止
创建规则引擎:
rulesengine rulesengine = new defaultrulesengine(); // or rulesengine rulesengine = new inferencerulesengine();
然后,注册规则
rulesengine.fire(rules, facts);
规则引擎有一些可配置的参数,如下图所示:
举个栗子:
rulesengineparameters parameters = new rulesengineparameters() .ruleprioritythreshold(10) .skiponfirstappliedrule(true) .skiponfirstfailedrule(true) .skiponfirstnontriggeredrule(true); rulesengine rulesengine = new defaultrulesengine(parameters);
2.4. 定义规则监听器
通过实现rulelistener接口
public interface rulelistener { /** * triggered before the evaluation of a rule. * * @param rule being evaluated * @param facts known before evaluating the rule * @return true if the rule should be evaluated, false otherwise */ default boolean beforeevaluate(rule rule, facts facts) { return true; } /** * triggered after the evaluation of a rule. * * @param rule that has been evaluated * @param facts known after evaluating the rule * @param evaluationresult true if the rule evaluated to true, false otherwise */ default void afterevaluate(rule rule, facts facts, boolean evaluationresult) { } /** * triggered on condition evaluation error due to any runtime exception. * * @param rule that has been evaluated * @param facts known while evaluating the rule * @param exception that happened while attempting to evaluate the condition. */ default void onevaluationerror(rule rule, facts facts, exception exception) { } /** * triggered before the execution of a rule. * * @param rule the current rule * @param facts known facts before executing the rule */ default void beforeexecute(rule rule, facts facts) { } /** * triggered after a rule has been executed successfully. * * @param rule the current rule * @param facts known facts after executing the rule */ default void onsuccess(rule rule, facts facts) { } /** * triggered after a rule has failed. * * @param rule the current rule * @param facts known facts after executing the rule * @param exception the exception thrown when attempting to execute the rule */ default void onfailure(rule rule, facts facts, exception exception) { } }
3. 示例
<project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelversion>4.0.0</modelversion> <groupid>com.cjs.example</groupid> <artifactid>easy-rules-quickstart</artifactid> <version>1.0.0-snapshot</version> <packaging>jar</packaging> <dependencies> <dependency> <groupid>org.jeasy</groupid> <artifactid>easy-rules-core</artifactid> <version>4.0.0</version> </dependency> <dependency> <groupid>org.jeasy</groupid> <artifactid>easy-rules-support</artifactid> <version>4.0.0</version> </dependency> <dependency> <groupid>org.jeasy</groupid> <artifactid>easy-rules-mvel</artifactid> <version>4.0.0</version> </dependency> <dependency> <groupid>org.slf4j</groupid> <artifactid>slf4j-simple</artifactid> <version>1.7.30</version> </dependency> </dependencies> </project>
4. 扩展
规则本质上是一个函数,如y=f(x1,x2,..,xn)
规则引擎就是为了解决业务代码和业务规则分离的引擎,是一种嵌入在应用程序中的组件,实现了将业务决策从应用程序代码中分离。
还有一种常见的方式是java+groovy来实现,java内嵌groovy脚本引擎进行业务规则剥离。
到此这篇关于java规则引擎easy rules的使用介绍的文章就介绍到这了,更多相关java规则引擎easy rules内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: 一些PhotoShop常用的快捷键
下一篇: 桂林适合夏天旅游的景点