SpringBoot2 integrate Drools rules engine to achieve efficient business rules

This article Source: GitHub · Click here || GitEE · Click here

A, Drools engine Introduction

1. Introduction basis

Drools is a java-based rules engine, open source can be complicated liberation from hard-coded rules out, in a regular script is stored in a file, so that the rule change does not need to amend the code to restart the machine to be online immediately environmental effect. Have easy access to corporate strategy, easy to adjust and easy to manage, as an open source business rules engine, in line with the industry standard, high speed, high efficiency.

2, Rule Syntax

(1), the presentation drl file format

package droolRule ;
import org.slf4j.Logger
import org.slf4j.LoggerFactory ;
dialect  "java"
rule "paramcheck1"
    when 
    then
        final Logger LOGGER = LoggerFactory.getLogger("param-check-one 规则引擎") ;
        LOGGER.info("参数");
end

(2), Syntax

· 文件格式
可以 .drl、xml文件,也可以Java代码块硬编码;
· package
规则文件中,package是必须定义的,必须放在规则文件第一行;
· import
规则文件使用到的外部变量,可以是一个类,也可以是类中的可访问的静态方法;
· rule
定义一个规则。paramcheck1规则名。规则通常包含三个部分:属性、条件、结果;

Second, the integration framework SpringBoot

1, project structure

SpringBoot2 integrate Drools rules engine to achieve efficient business rules

2, rely on the core

<!--drools规则引擎-->
<dependency>
    <groupId>org.drools</groupId>
    <artifactId>drools-core</artifactId>
    <version>7.6.0.Final</version>
</dependency>
<dependency>
    <groupId>org.drools</groupId>
    <artifactId>drools-compiler</artifactId>
    <version>7.6.0.Final</version>
</dependency>
<dependency>
    <groupId>org.drools</groupId>
    <artifactId>drools-templates</artifactId>
    <version>7.6.0.Final</version>
</dependency>
<dependency>
    <groupId>org.kie</groupId>
    <artifactId>kie-api</artifactId>
    <version>7.6.0.Final</version>
</dependency>
<dependency>
    <groupId>org.kie</groupId>
    <artifactId>kie-spring</artifactId>
    <version>7.6.0.Final</version>
</dependency>

3, the configuration file

@Configuration
public class RuleEngineConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(RuleEngineConfig.class) ;
    private static final String RULES_PATH = "droolRule/";
    private final KieServices kieServices = KieServices.Factory.get();
    @Bean
    public KieFileSystem kieFileSystem() throws IOException {
        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        Resource[] files = resourcePatternResolver.getResources("classpath*:" + RULES_PATH + "*.*");
        String path = null;
        for (Resource file : files) {
            path = RULES_PATH + file.getFilename();
            LOGGER.info("path="+path);
            kieFileSystem.write(ResourceFactory.newClassPathResource(path, "UTF-8"));
        }
        return kieFileSystem;
    }
    @Bean
    public KieContainer kieContainer() throws IOException {
        KieRepository kieRepository = kieServices.getRepository();
        kieRepository.addKieModule(kieRepository::getDefaultReleaseId);
        KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem());
        kieBuilder.buildAll();
        return kieServices.newKieContainer(kieRepository.getDefaultReleaseId());
    }
    @Bean
    public KieBase kieBase() throws IOException {
        return kieContainer().getKieBase();
    }
    @Bean
    public KieSession kieSession() throws IOException {
        return kieContainer().newKieSession();
    }
    @Bean
    public KModuleBeanFactoryPostProcessor kiePostProcessor() {
        return new KModuleBeanFactoryPostProcessor();
    }
}

Such environmental integration is complete.

Third, the demo case

1, the rules file

  • Rule number one
    dialect  "java"
    rule "paramcheck1"
    salience 99
    when queryParam : QueryParam(paramId != null && paramSign.equals("+"))
        resultParam : RuleResult()
    then
        final Logger LOGGER = LoggerFactory.getLogger("param-check-one 规则引擎") ;
        LOGGER.info("参数:getParamId="+queryParam.getParamId()+";getParamSign="+queryParam.getParamSign());
        RuleEngineServiceImpl ruleEngineService = new RuleEngineServiceImpl() ;
        ruleEngineService.executeAddRule(queryParam);
        resultParam.setPostCodeResult(true);
    end
  • Rule number two
    dialect  "java"
    rule "paramcheck2"
    salience 88
    when queryParam : QueryParam(paramId != null && paramSign.equals("-"))
        resultParam : RuleResult()
    then
        final Logger LOGGER = LoggerFactory.getLogger("param-check-two 规则引擎") ;
        LOGGER.info("参数:getParamId="+queryParam.getParamId()+";getParamSign="+queryParam.getParamSign());
        RuleEngineServiceImpl ruleEngineService = new RuleEngineServiceImpl() ;
        ruleEngineService.executeRemoveRule(queryParam);
        resultParam.setPostCodeResult(true);
    end

Rule Description:

A, the salience value, the more preferentially executed;

B, the flow rule: If paramId not null, the parameter identification number is +, perform add rules, - number, performing removal operation rules.

2, rule code execution

@Service
public class RuleEngineServiceImpl implements RuleEngineService {
    private static final Logger LOGGER = LoggerFactory.getLogger(RuleEngineServiceImpl.class) ;
    @Override
    public void executeAddRule(QueryParam param) {
        LOGGER.info("参数数据:"+param.getParamId()+";"+param.getParamSign());
        ParamInfo paramInfo = new ParamInfo() ;
        paramInfo.setId(param.getParamId());
        paramInfo.setParamSign(param.getParamSign());
        paramInfo.setCreateTime(new Date());
        paramInfo.setUpdateTime(new Date());
        ParamInfoService paramInfoService = (ParamInfoService)SpringContextUtil.getBean("paramInfoService") ;
        paramInfoService.insertParam(paramInfo);
    }
    @Override
    public void executeRemoveRule(QueryParam param) {
        LOGGER.info("参数数据:"+param.getParamId()+";"+param.getParamSign());
        ParamInfoService paramInfoService = (ParamInfoService)SpringContextUtil.getBean("paramInfoService") ;
        ParamInfo paramInfo = paramInfoService.selectById(param.getParamId());
        if (paramInfo != null){
            paramInfoService.removeById(param.getParamId()) ;
        }
    }
}

3, the rules call interface

@RestController
@RequestMapping("/rule")
public class RuleController {
    @Resource
    private KieSession kieSession;
    @Resource
    private RuleEngineService ruleEngineService ;
    @RequestMapping("/param")
    public void param (){
        QueryParam queryParam1 = new QueryParam() ;
        queryParam1.setParamId("1");
        queryParam1.setParamSign("+");
        QueryParam queryParam2 = new QueryParam() ;
        queryParam2.setParamId("2");
        queryParam2.setParamSign("-");
        // 入参
        kieSession.insert(queryParam1) ;
        kieSession.insert(queryParam2) ;
        kieSession.insert(this.ruleEngineService) ;
        // 返参
        RuleResult resultParam = new RuleResult() ;
        kieSession.insert(resultParam) ;
        kieSession.fireAllRules() ;
    }
}

In this way, the full case is over.

Fourth, the source address

GitHub·地址
https://github.com/cicadasmile/middle-ware-parent
GitEE·地址
https://gitee.com/cicadasmile/middle-ware-parent

SpringBoot2 integrate Drools rules engine to achieve efficient business rules

Guess you like

Origin blog.51cto.com/14439672/2444594