springboot整合EasyRules读取规则文件rule.json【简单实现】,EasyRules规则引擎读取配置json文件

废话不多说。

本次测试时的依赖及版本
<dependency>
  <groupId>org.jeasy</groupId>
  <artifactId>easy-rules-core</artifactId>
  <version>4.1.0</version>
</dependency>
<dependency>
  <groupId>org.jeasy</groupId>
  <artifactId>easy-rules-support</artifactId>
  <version>4.1.0</version>
</dependency>
<dependency>
  <groupId>org.jeasy</groupId>
  <artifactId>easy-rules-mvel</artifactId>
  <version>4.1.0</version>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>
创建rule.json文件,并定义规则
[
  {
    "name": "数字规则1",
    "description": "数字是否等于5",
    "condition": "#number % 5 == 0",
    "actions": [
      "(#number)"
    ],
    "priority": 20
  },
  {
    "name": "数字规则2",
    "description": "数字计算差值",
    "condition": "#number % 5 == 0",
    "actions": [
      "(#number) + (#number - 5 == 0 ? '差值等于0了' : '差值不等于0了')"
    ],
    "priority": 20
  }
]
读取json文件
import org.jeasy.rules.api.Facts;
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.support.RuleDefinition;
import org.jeasy.rules.support.reader.JsonRuleDefinitionReader;
import org.junit.Test;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

public class SpringELTest {
    @Test
    public void test() throws Exception {
        Rules rules = new Rules();
        // 1、创建Json规则定义读取器
        JsonRuleDefinitionReader jsonRuleDefinitionReader = new JsonRuleDefinitionReader();
        InputStream resourceAsStream = JsonRuleDefinitionReader.class.getResourceAsStream(("/path/rule.json"));
        if (resourceAsStream == null) return;
        // 2、读取规则定义的json文件
        List<RuleDefinition> ruleDefinitionList = jsonRuleDefinitionReader.read(new InputStreamReader(resourceAsStream));
        for (RuleDefinition ruleDefinition : ruleDefinitionList) {
            // 3、将文件中的规则读取出来后,在通过链式编程创建规则
            RuleBuilder ruleBuilder = new RuleBuilder()
            .name(ruleDefinition.getName())
            .priority(ruleDefinition.getPriority())
            .description(ruleDefinition.getDescription());

            // 4、判断是否满足定义的规则
            ruleBuilder.when(facts -> {
                Boolean result = this.parseException(ruleDefinition.getCondition(), facts.asMap(), Boolean.class);
                System.out.println("result = " + result);
                return result;
            });

            // 【如果第4步,满足了定义的规则(即返回true),则会进行第5步】
            // 5、获取所有可能需要执行规则
            for (String action : ruleDefinition.getActions()) {
                ruleBuilder.then(facts -> {
                    // 获取最终满足了第4步的执行结果;【如果不满足第4步,则不会执行该操作】
                    String endResult = this.parseException(action, facts.asMap(), String.class);
                    System.out.println("endResult = " + endResult);
                });
            }
            // 将获取文件中的规则通过RuleBuilder重新创建的规则,注册到规则中
            rules.register(ruleBuilder.build());
        }

        // 创建默认的规则引擎
        RulesEngine rulesEngine = new DefaultRulesEngine();
        Facts facts = new Facts();
        // 通过改变number的值,测试
        facts.put("number", 5);
        // 规则引擎中
        rulesEngine.fire(rules, facts);
        
    }

    private <T> T parseException(String expressionStr, Map<String, Object> variables, Class<T> clazz) {
        // 创建一个SpelExpressionParser对象
        SpelExpressionParser parser = new SpelExpressionParser();
        Expression expression = parser.parseExpression(expressionStr);

        // 创建一个StandardEvaluationContext对象,用于存储变量和函数
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setVariables(variables);

        // 使用Expression对象和EvaluationContext对象计算结果
        T value = expression.getValue(context, clazz);
        return value;
    }
}

最终执行结果:

json文件中的规则:"数字规则1","数字规则2"都会执行;

  • 16
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值