崛起于Springboot2.X之集成规则引擎Drools(41) 原 荐

栏目: Java · 发布时间: 5年前

1、创建Springboot项目,勾选Web模块和lombok插件

崛起于Springboot2.X之集成规则引擎Drools(41) 原 荐

崛起于Springboot2.X之集成规则引擎Drools(41) 原 荐

2、添加pom其他依赖

<dependency>
    <groupId>org.kie</groupId>
    <artifactId>kie-spring</artifactId>
    <version>7.11.0.Final</version>
    <exclusions>
        <exclusion>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.drools</groupId>
    <artifactId>drools-compiler</artifactId>
    <version>7.11.0.Final</version>
</dependency>

3、创建实体类

@Data
public class Address {

    private String postCode;

    private String street;

    private String state;
}
@Data
public class AddressCheckResult {
    //true通过校验,false 未通过
    private boolean postCodeResult = false;
}

4、配置类

import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.*;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.kie.spring.KModuleBeanFactoryPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;


/**
 * @Author:Mujiutian
 * @Description:
 * @Date: Created in 下午2:45 2018/12/14
 */
@Configuration
public class DroolsAutoConfiguration {

    //rule的存放位置
    private static final String RULES_PATH = "rules/";

    @Bean
    @ConditionalOnMissingBean(KieFileSystem.class)
    public KieFileSystem kieFileSystem() throws IOException {
        KieFileSystem kieFileSystem = getKieServices().newKieFileSystem();
        for (Resource file : getRuleFiles()) {
            String path = RULES_PATH + file.getFilename();
            kieFileSystem.write(ResourceFactory.newClassPathResource(path, "UTF-8"));
        }
        return kieFileSystem;
    }

    /**
     * 这里要引入 org.springframework.core.io.Resource  包
     *
     * @return
     * @throws IOException
     */
    private Resource[] getRuleFiles() throws IOException {
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        return resourcePatternResolver.getResources("classpath*:" + RULES_PATH + "**/*.*");
    }

    @Bean
    @ConditionalOnMissingBean(KieContainer.class)
    public KieContainer kieContainer() throws IOException {
        final KieRepository kieRepository = getKieServices().getRepository();

        kieRepository.addKieModule(new KieModule() {
            public ReleaseId getReleaseId() {
                return kieRepository.getDefaultReleaseId();
            }
        });

        KieBuilder kieBuilder = getKieServices().newKieBuilder(kieFileSystem());
        kieBuilder.buildAll();

        return getKieServices().newKieContainer(kieRepository.getDefaultReleaseId());
    }

    private KieServices getKieServices() {
        return KieServices.Factory.get();
    }

    @Bean
    @ConditionalOnMissingBean(KieBase.class)
    public KieBase kieBase() throws IOException {
        return kieContainer().getKieBase();
    }

    @Bean
    @ConditionalOnMissingBean(KieSession.class)
    public KieSession kieSession() throws IOException {
        return kieContainer().newKieSession();
    }

    @Bean
    @ConditionalOnMissingBean(KModuleBeanFactoryPostProcessor.class)
    public KModuleBeanFactoryPostProcessor kiePostProcessor() {
        return new KModuleBeanFactoryPostProcessor();
    }
}

5、创建drools特有的xml

崛起于Springboot2.X之集成规则引擎Drools(41) 原 荐

<?xml version="1.0" encoding="UTF-8" ?>
<kmodule xmlns="http://www.drools.org/xsd/kmodule">
    <kbase name="rules" packages="mujiutian.rules">
        <ksession name="ksession-rule"/>
    </kbase>
</kmodule>

这个packages 要和下面的规则文件对应的名字一致,不然会报错

6、编写drools规则

package mujiutian.rules;

import com.mjt.drools.entity.Address;
import com.mjt.drools.entity.AddressCheckResult;


rule "Rules"
    when
        adress : Address(postCode != null,postCode matches "([0-9]{5})")
        checkResult: AddressCheckResult();
    then
        checkResult.setPostCodeResult(true);
        System.out.println("规则中打印日志:校验通过");
end

这个package默认生成是static,要修改一些,不然会报错,同时要和上面xml中的内容一样才行,rule 后面加的"" 是描述内容,可以写任何内容

下面就不可以随意写了。

6、编写controller层

import org.kie.api.runtime.KieSession;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @Author:Mujiutian
 * @Description:
 * @Date: Created in 下午3:14 2018/12/14
 */
@RestController
@RequestMapping(value = "/drools")
public class DroolsController {

    @Resource
    KieSession kieSession;

    @GetMapping(value = "/address")
    public void test1(){
        Address address = new Address();
        address.setPostCode("99425");

        AddressCheckResult result = new AddressCheckResult();
        kieSession.insert(address);
        kieSession.insert(result);
        int ruleFiredCount = kieSession.fireAllRules();
        System.out.println("触发了"+ruleFiredCount+"条规则");

        if (result.isPostCodeResult()){
            System.out.println("规则校验通过");
        }
    }
}

7、运行项目,测试

崛起于Springboot2.X之集成规则引擎Drools(41) 原 荐

借鉴于:https://blog.csdn.net/qq_21383435/article/details/82873711  基本完全复制的代码,如果可以也可以进入他的博客专栏,感谢!


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Spring Into HTML and CSS

Spring Into HTML and CSS

Molly E. Holzschlag / Addison-Wesley Professional / 2005-5-2 / USD 34.99

The fastest route to true HTML/CSS mastery! Need to build a web site? Or update one? Or just create some effective new web content? Maybe you just need to update your skills, do the job better. Welco......一起来看看 《Spring Into HTML and CSS》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具