1. 程式人生 > >《Drools7.0.0.Final規則引擎教程》之Springboot整合

《Drools7.0.0.Final規則引擎教程》之Springboot整合

本來準備按部就班的一章一章更新Drools相關教程,怎奈QQ群組(593177274)有朋友急需Springboot與Drools的整合demo,於是抽出時間寫了一個,現在拿出來分享一下。加入群組可免費下載demo,也可以在CSDN下載頻道下載:Springboot&Drools demo

pom檔案

引入了springboot和drools的依賴,同時引入了kie-spring的整合依賴。

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId
>
<artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.kie</groupId> <artifactId>kie-spring</artifactId> <version>${drools.version}</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>${drools.version}</version> </dependency> </dependencies>

配置類

基於springboot的初始化配置:

@Configuration
public class DroolsAutoConfiguration {

    private static final String RULES_PATH = "rules/";

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

    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();
    }
}

Springboot啟動類

@SpringBootApplication
public class SpringBootDroolsApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootDroolsApplication.class, args);
    }
}

實體類

public class Address {

    private String postcode;

    private String street;

    private String state;
    // 省略getter/setter
}

規則返回結果類

public class AddressCheckResult {

    private boolean postCodeResult = false; // true:通過校驗;false:未通過校驗
    // 省略getter/setter
}

規則檔案

package plausibcheck.adress

import com.secbro.model.Address;
import com.secbro.model.fact.AddressCheckResult;

rule "Postcode should be filled with exactly 5 numbers"

    when
        address : Address(postcode != null, postcode matches "([0-9]{5})")
        checkResult : AddressCheckResult();
    then
        checkResult.setPostCodeResult(true);
        System.out.println("規則中列印日誌:校驗通過!");
end

測試Controller

@RequestMapping("/test")
@Controller
public class TestController {

    @Resource
    private KieSession kieSession;

    @ResponseBody
    @RequestMapping("/address")
    public void test(){
        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("規則校驗通過");
        }

    }
}

後語

你的支援是我努力的最大動力!社群的建立離不開你的支援。此係列課程正在持續更新中,相關討論QQ(593177274)已經建立,歡迎大家加入討論。如有疑問可以留言也可以傳送本人郵箱[email protected]。擊此處關注Drools部落格專欄的持續更新《Drools部落格專欄》
這裡寫圖片描述