溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot集成easy-rules規(guī)則引擎的流程是什么

發(fā)布時間:2023-03-28 11:58:20 來源:億速云 閱讀:342 作者:iii 欄目:開發(fā)技術

這篇文章主要講解了“SpringBoot集成easy-rules規(guī)則引擎的流程是什么”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“SpringBoot集成easy-rules規(guī)則引擎的流程是什么”吧!

一、概述

通過將業(yè)務規(guī)則配置的配置文件中,可以精簡代碼,同時已于維護,當規(guī)則修改時,只需要修改配置文件即可。easy-rules是一個小巧的規(guī)則引擎,支持spring的SPEL表達式,同時還支持 Apache JEXL 表達式和 MVL 表達式。

二、項目中加入依賴

在項目的gradle中增加依賴關系。

build.gradle:

plugins {
    id 'org.springframework.boot' version '3.0.5'
    id 'io.spring.dependency-management' version '1.1.0'
    id 'java'
}

group = 'cn.springcamp'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
    testCompileOnly {
        extendsFrom testAnnotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation "org.springframework.boot:spring-boot-starter-json"
    implementation 'org.springframework.boot:spring-boot-starter-validation'
    implementation 'org.jeasy:easy-rules-core:4.1.0'
    implementation 'org.jeasy:easy-rules-spel:4.1.0'
    implementation 'org.jeasy:easy-rules-support:4.1.0'
    annotationProcessor 'org.projectlombok:lombok'
    testAnnotationProcessor 'org.projectlombok:lombok'
    testImplementation "org.springframework.boot:spring-boot-starter-test"
    testImplementation 'org.junit.vintage:junit-vintage-engine'
    testImplementation 'org.junit.vintage:junit-vintage-engine'
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:2022.0.1"
    }
}

test {
    useJUnitPlatform()
}

三、配置文件

示例程序將業(yè)務規(guī)則放到配置文件中,業(yè)務規(guī)則配置文件(demo-rule.yml)代碼:

name: "age rule"
description: ""
priority: 1
condition: "#person.getAdult() == false"
actions:
  - "T(java.lang.System).out.println(\"Shop: Sorry, you are not allowed to buy alcohol\")"
  - "#person.setAdult(true)"
  - "#person.setAge(18)"
---
name: "alcohol rule"
description: ""
priority: 1
condition: "#person.getAdult() == true"
actions:
  - "T(java.lang.System).out.println(\"Shop: you are now allowed to buy alcohol\")"

配置文件中的規(guī)則通過 condition 進行配置,當滿足規(guī)則時,會調用 actions 中配置的動作。

示例項目使用了spring的SPEL表達式進行規(guī)則配置,配置文件中配置了2個規(guī)則,第一個規(guī)則通過 person這個spring bean中的getAdult()判斷是否滿足規(guī)則,滿足規(guī)則時調用三個方法。

在spring-boot本身的配置文件中 application.yml 配置規(guī)則文件:

rule:
  skip-on-first-failed-rule: true
  skip-on-first-applied-rule: false
  skip-on-first-non-triggered-rule: true
  rules:
    - rule-id: "demo"
      rule-file-location: "classpath:demo-rule.yml"

四、代碼中對規(guī)則引擎進行配置

通過 RuleEngineConfig這個spring的配置類對規(guī)則引擎進行配置:

@Slf4j
@EnableConfigurationProperties(RuleEngineConfigProperties.class)
@Configuration
public class RuleEngineConfig implements BeanFactoryAware {
    @Autowired(required = false)
    private List<RuleListener> ruleListeners;
    @Autowired(required = false)
    private List<RulesEngineListener> rulesEngineListeners;
    private BeanFactory beanFactory;
    @Bean
    public RulesEngineParameters rulesEngineParameters(RuleEngineConfigProperties properties) {
        RulesEngineParameters parameters = new RulesEngineParameters();
        parameters.setSkipOnFirstAppliedRule(properties.isSkipOnFirstAppliedRule());
        parameters.setSkipOnFirstFailedRule(properties.isSkipOnFirstFailedRule());
        parameters.setSkipOnFirstNonTriggeredRule(properties.isSkipOnFirstNonTriggeredRule());
        return parameters;
    }
    @Bean
    public RulesEngine rulesEngine(RulesEngineParameters rulesEngineParameters) {
        DefaultRulesEngine rulesEngine = new DefaultRulesEngine(rulesEngineParameters);
        if (!CollectionUtils.isEmpty(ruleListeners)) {
            rulesEngine.registerRuleListeners(ruleListeners);
        }
        if (!CollectionUtils.isEmpty(rulesEngineListeners)) {
            rulesEngine.registerRulesEngineListeners(rulesEngineListeners);
        }
        return rulesEngine;
    }
    @Bean
    public BeanResolver beanResolver() {
        return new BeanFactoryResolver(beanFactory);
    }
    @Bean
    public RuleEngineTemplate ruleEngineTemplate(RuleEngineConfigProperties properties, RulesEngine rulesEngine) {
        RuleEngineTemplate ruleEngineTemplate = new RuleEngineTemplate();
        ruleEngineTemplate.setBeanResolver(beanResolver());
        ruleEngineTemplate.setProperties(properties);
        ruleEngineTemplate.setRulesEngine(rulesEngine);
        return ruleEngineTemplate;
    }
    @Bean
    public RuleListener defaultRuleListener() {
        return new RuleListener() {
            @Override
            public boolean beforeEvaluate(Rule rule, Facts facts) {
                return true;
            }
            @Override
            public void afterEvaluate(Rule rule, Facts facts, boolean b) {
                log.info("-----------------afterEvaluate-----------------");
                log.info(rule.getName() + rule.getDescription() + facts.toString());
            }
            @Override
            public void beforeExecute(Rule rule, Facts facts) {
                log.info("-----------------beforeExecute-----------------");
                log.info(rule.getName() + rule.getDescription() + facts.toString());
            }
            @Override
            public void onSuccess(Rule rule, Facts facts) {
                log.info("-----------------onSuccess-----------------");
                log.info(rule.getName() + rule.getDescription() + facts.toString());
            }
            @Override
            public void onFailure(Rule rule, Facts facts, Exception e) {
                log.info("-----------------onFailure-----------------");
                log.info(rule.getName() + "----------" + rule.getDescription() + facts.toString() + e.toString());
            }
        };
    }
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}

配置文件中配置了 ruleEngineTemplate這個spring bean,通過ruleEngineTemplate觸發(fā)規(guī)則引擎的執(zhí)行。

五、執(zhí)行規(guī)則引擎

ruleEngineTemplate配置好后,我們可以在業(yè)務代碼中執(zhí)行規(guī)則引擎,處理配置文件中配置的業(yè)務規(guī)則:

最為演示,我們將規(guī)則引擎的執(zhí)行代碼放到了 Application 的 run 方法中,程序啟動后立即執(zhí)行規(guī)則引擎:

@SpringBootApplication
public class Application implements CommandLineRunner {
    @Autowired
    RuleEngineTemplate ruleEngineTemplate;
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    @Override
    public void run(String... args) {
        Person person = new Person();
        Facts facts = new Facts();
        facts.put("person", person);
        ruleEngineTemplate.fire("demo", facts);
    }
}

程序執(zhí)行后可以看到控制臺里打印了 Shop: Sorry, you are not allowed to buy alcohol,這個內容對應的是我們在規(guī)則文件中的actions中配置的 "T(java.lang.System).out.println(\"Shop: Sorry, you are not allowed to buy alcohol\")",說明規(guī)則成功執(zhí)行了。

感謝各位的閱讀,以上就是“SpringBoot集成easy-rules規(guī)則引擎的流程是什么”的內容了,經過本文的學習后,相信大家對SpringBoot集成easy-rules規(guī)則引擎的流程是什么這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI