我的日记 我的日记

记录精彩的程序人生

目录
Drools (一) -简介
/  

Drools (一) -简介

简介

Drools引擎是Drools的规则引擎。Drools引擎存储,处理和评估数据,以执行您定义的业务规则或决策模型。Drools引擎的基本功能是将传入的数据或事实与规则条件相匹配,并确定是否以及如何执行规则

样例

1.新建一个spring boot 项目

2.引入maven库

 <dependency>
            <groupId>org.drools</groupId>
            <artifactId>drools-core</artifactId>
            <version>7.34.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.drools</groupId>
            <artifactId>drools-compiler</artifactId>
            <version>7.34.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.drools</groupId>
            <artifactId>drools-templates</artifactId>
            <version>7.34.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.kie</groupId>
            <artifactId>kie-api</artifactId>
            <version>7.34.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.kie</groupId>
            <artifactId>kie-spring</artifactId>
            <version>7.34.0.Final</version>
        </dependency>

3.新建一个配置类如下

import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
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.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author yudong
 * @version 1.0
 * @date 2020/3/23 5:37 下午
 * @modified By
 */
@Component
@Configurable
public class DroolsConfig {

    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*:*.drl");
        for (Resource file : files) {
            kieFileSystem.write(ResourceFactory.newClassPathResource(file.getFilename(), "UTF-8"));
        }
        return kieFileSystem;
    }

    @Bean
    public KieContainer kieContainer( KieFileSystem kieFileSystem) 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( KieContainer kieContainer) throws IOException {
        return kieContainer.getKieBase();
    }
    @Bean
    public KieSession kieSession( KieContainer kieContainer) throws IOException {
        return kieContainer.newKieSession();
    }
    @Bean
    public KModuleBeanFactoryPostProcessor kiePostProcessor() {
        return new KModuleBeanFactoryPostProcessor();
    }
}

4.创建两个实体类 QueryParam 和 RuleResult

/**
 * @author yudong
 * @version 1.0
 * @date 2020/3/23 6:15 下午
 * @modified By
 */
public class QueryParam {

    private String test;

    public String getTest() {
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }
}
/**
 * @author yudong
 * @version 1.0
 * @date 2020/3/23 6:16 下午
 * @modified By
 */
public class RuleResult {

    private Boolean result;

    public Boolean getResult() {
        return result;
    }

    public void setResult(Boolean result) {
        this.result = result;
    }
}

5.在resources资源文件夹下创建test.drl文件,内容如下

package droolRule ;
import com.example.demo.*
dialect  "java"
rule "test1"
    salience 99
    when queryParam :  QueryParam(test != null)
         resultParam : RuleResult()
    then
        System.out.println("参数内容:"+queryParam.getTest());
        resultParam.setResult(true);
end

6.创建测试Controller

import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


/**
 * @author yudong
 * @version 1.0
 * @date 2020/2/11 2:38 下午
 * @modified By
 */
@ResponseBody
@Controller
public class TestController {
    

    @Autowired
    private KieSession kieSession;
    /**
     * 运营后台-登录
     * @return
     * @throws Exception
     */
  @PostMapping("/test")
  public String test()throws Exception{
      QueryParam queryParam = new QueryParam();
      queryParam.setTest("11111");
      RuleResult ruleResult = new RuleResult();
      kieSession.insert(queryParam);
      kieSession.insert(ruleResult);
      kieSession.fireAllRules();
      System.out.println(ruleResult.getResult());
      return "";
   }


}

7.测试结果如下输出

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.9.RELEASE)

2020-03-24 18:15:16.966  INFO 21984 --- [           main] com.example.demo.DemoApplication         : Starting DemoApplication on yudongdeMacBook-Pro.local with PID 21984 (/Users/yudong/Documents/Erdos/demo/target/classes started by yudong in /Users/yudong/Documents/Erdos/demo)
2020-03-24 18:15:16.971  INFO 21984 --- [           main] com.example.demo.DemoApplication         : No active profile set, falling back to default profiles: default
2020-03-24 18:15:18.088  INFO 21984 --- [           main] o.k.s.KModuleBeanFactoryPostProcessor    : :: BeanFactoryPostProcessor::postProcessBeanFactory called ::
2020-03-24 18:15:18.098  WARN 21984 --- [           main] o.d.c.k.b.impl.ClasspathKieProject       : Unable to find pom.properties in /Users/yudong/Documents/Erdos/demo/target/classes/com/example/demo
2020-03-24 18:15:18.193  INFO 21984 --- [           main] o.d.c.k.b.impl.ClasspathKieProject       : Recursed up folders, found and used pom.xml /Users/yudong/Documents/Erdos/demo/pom.xml
2020-03-24 18:15:18.195  INFO 21984 --- [           main] o.k.s.KModuleBeanFactoryPostProcessor    : Found project with releaseId: com.example:demo:0.0.1-SNAPSHOT
2020-03-24 18:15:20.204  WARN 21984 --- [           main] io.undertow.websockets.jsr               : UT026010: Buffer pool was not set on WebSocketDeploymentInfo, the default pool will be used
2020-03-24 18:15:20.275  INFO 21984 --- [           main] io.undertow.servlet                      : Initializing Spring embedded WebApplicationContext
2020-03-24 18:15:20.275  INFO 21984 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3238 ms
2020-03-24 18:15:21.411  WARN 21984 --- [           main] o.d.c.kie.builder.impl.KieBuilderImpl    : File 'test.drl' is in folder '' but declares package 'droolRule'. It is advised to have a correspondance between package and folder names.
2020-03-24 18:15:23.238  INFO 21984 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-03-24 18:15:23.615  INFO 21984 --- [           main] com.example.demo.BodyReaderFilter        : filter init
2020-03-24 18:15:23.628  INFO 21984 --- [           main] org.xnio                                 : XNIO version 3.3.8.Final
2020-03-24 18:15:23.646  INFO 21984 --- [           main] org.xnio.nio                             : XNIO NIO Implementation Version 3.3.8.Final
2020-03-24 18:15:23.788  INFO 21984 --- [           main] o.s.b.w.e.u.UndertowServletWebServer     : Undertow started on port(s) 8080 (http) with context path ''
2020-03-24 18:15:23.795  INFO 21984 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 7.442 seconds (JVM running for 9.421)
2020-03-24 18:16:14.257  INFO 21984 --- [  XNIO-1 task-1] io.undertow.servlet                      : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-03-24 18:16:14.257  INFO 21984 --- [  XNIO-1 task-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-03-24 18:16:14.274  INFO 21984 --- [  XNIO-1 task-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 17 ms
参数内容:11111
true


标题:Drools (一) -简介
作者:adongs
地址:https://adongs.com/articles/2019/08/15/1565852227229.html