规则引擎----easy rules

一、规则引擎的作用

将复杂的if else判断剥离出来

二、使用

2.1、引入POM

		<!--easy rules核心库-->
        <dependency>
            <groupId>org.jeasy</groupId>
            <artifactId>easy-rules-core</artifactId>
            <version>3.3.0</version>
        </dependency>

        <!--规则定义文件格式,支持json,yaml等-->
        <dependency>
            <groupId>org.jeasy</groupId>
            <artifactId>easy-rules-support</artifactId>
            <version>3.3.0</version>
        </dependency>

        <!--支持mvel规则语法库-->
        <dependency>
            <groupId>org.jeasy</groupId>
            <artifactId>easy-rules-mvel</artifactId>
            <version>3.3.0</version>

2.2、编写规则

2.2.1、注解
package com.xx.rule.number;

import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Fact;
import org.jeasy.rules.annotation.Rule;

/**
 * @author aqi
 * @date 2023/5/6 16:03
 */
@Rule(name = "被3整除", description = "number如果被3整除,打印:number is 3", priority = 1)
public class ThreeRule {

    /**
     * Condition:条件判断注解:如果return true, 执行Action
     */
    @Condition
    public boolean isThree(@Fact("number") int number) {
        return number % 3 == 0;
    }

    /**
     * Action 执行方法注解
     */
    @Action
    public void threeAction(@Fact("number") int number) {
        System.out.println(number + ":可以被3整除");
    }
}

2.2.2、表达式
MVELRule ageRule = new MVELRule()
                .name("age rule")
                .description("判断这个人是否成年,是否可以饮酒")
                .priority(1)
                .when("person.age > 18").then("person.setAdult(true);");
2.2.3 yml配置文件
name: "alcohol rule"
description: "children are not allowed to buy alcohol"
priority: 2
condition: "person.isAdult() == false"
actions:
  - "System.out.println(\"你还未满18岁!\");"
2.2.4 组合规则
UnitRuleGroup myUnitRuleGroup = new UnitRuleGroup("myUnitRuleGroup", "组合规则");
        myUnitRuleGroup.addRule(ageRule);
        myUnitRuleGroup.addRule(alcoholRule);
2.2.5 组合规则说明
说明
UnitRuleGroup要么应用所有规则,要么不应用任何规则(AND逻辑)
ActivationRuleGroup它触发第一个适用规则,并忽略组中的其他规则(XOR逻辑)
ConditionalRuleGroup如果具有最高优先级的规则计算结果为true,则触发其余规则
2.2.6 字段说明
字段说明
name规则名称
description规则描述
priority规则执行顺序,越小越先执行
condition条件
actions满足条件之后的执行动作

2.3、规则使用

2.3.1、注解规则使用
package com.xx;

import com.xx.rule.number.ThreeRule;
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 Main {
    public static void main(String[] args) {
        // 创建规则执行引擎
        RulesEngine rulesEngine = new DefaultRulesEngine();
        // 创建规则
        Rules rules = new Rules();
        rules.register(new ThreeRule());
        // 设置参数
        Facts facts = new Facts();
        for (int i = 1; i <= 50; i++) {
            //规则因素,对应的name,要和规则里面的@Fact 一致
            facts.put("number", i);
            //执行规则
            rulesEngine.fire(rules, facts);
            System.out.println();
        }
    }
}
2.3.2、表达式和yml规则使用
package com.xx;

import com.xx.domain.Person;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rule;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import org.jeasy.rules.core.DefaultRulesEngine;
import org.jeasy.rules.core.RuleBuilder;
import org.jeasy.rules.mvel.MVELRuleFactory;
import org.jeasy.rules.support.YamlRuleDefinitionReader;
import org.springframework.util.ResourceUtils;

import java.io.FileReader;

/**
 * 基于MVEL表达式实现规则引擎
 * @author aqi
 */
public class ShopMain {
    public static void main(String[] args) throws Exception {
        Person person = new Person();
        person.setName("tom");
        person.setAge(20);
        Facts facts = new Facts();
        facts.put("person", person);

        // 表达式
        Rule ageRule = new RuleBuilder()
                .name("age rule")
                .description("判断这个人是否成年,是否可以饮酒")
                .when(e -> Integer.parseInt(e.get("person.age")) > 18)
                .then(e -> e.put("person.adult", true))
                .build();


        // yml配置文件
        Rule alcoholRule = new MVELRuleFactory(new YamlRuleDefinitionReader()).
                 createRule(new FileReader(ResourceUtils.getFile("classpath:alcohol-rule.yml")));

        Rules rules = new Rules();
        rules.register(ageRule);
        rules.register(alcoholRule);

        //创建规则执行引擎,并执行规则
        RulesEngine rulesEngine = new DefaultRulesEngine();
        rulesEngine.fire(rules, facts);
        System.out.println(person);

    }
}
2.3.1、规则引擎可配参数
参数说明
skipOnFirstAppliedRule当一个规则成功应用时,跳过余下的规则
skipOnFirstFailedRule当一个规则失败时,跳过余下的规则
skipOnFirstNonTriggeredRule当一个规则未触发时,跳过余下的规则
rulePriorityThreshold当优先级超过指定的阈值时,跳过余下的规则

通过如下方式设置

RulesEngineParameters parameters = new RulesEngineParameters().skipOnFirstAppliedRule(true);
        RulesEngine rulesEngine = new DefaultRulesEngine(parameters);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Easy-rules是一个轻量级的Java规则引擎,可以帮助我们在应用程序中使用规则来进行业务逻辑处理。在Spring-boot中使用Easy-rules需要以下步骤: 1. 添加Easy-rules依赖 在pom.xml文件中添加Easy-rules依赖: ```xml <dependency> <groupId>org.easyrules</groupId> <artifactId>easy-rules-core</artifactId> <version>4.1.0</version> </dependency> ``` 2. 创建规则 创建一个规则类,继承自`org.easyrules.core.BasicRule`,并实现`org.easyrules.api.Rules`接口中的方法。例如: ```java public class AdultRule extends BasicRule { private Person person; public AdultRule(Person person) { super("AdultRule", "Check if person is an adult", 1); this.person = person; } @Override public boolean evaluate() { return person.getAge() >= 18; } @Override public void execute() throws Exception { System.out.println(person.getName() + " is an adult"); } } ``` 3. 配置规则引擎 在Spring-boot的配置类中配置规则引擎: ```java @Configuration public class RuleEngineConfiguration { @Bean public RulesEngine rulesEngine() { return new DefaultRulesEngine(); } } ``` 4. 执行规则 在需要执行规则的地方,注入规则引擎,然后将规则添加到规则引擎中并执行: ```java @Autowired private RulesEngine rulesEngine; public void executeRules(Person person) { Rules rules = new Rules(); rules.register(new AdultRule(person)); rulesEngine.fire(rules); } ``` 这样就可以在Spring-boot中使用Easy-rules规则引擎了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值