编程语言
首页 > 编程语言> > JAVA drools规则引擎决策表使用

JAVA drools规则引擎决策表使用

作者:互联网

本编使用xls文件生成决策表,来动态跟新规则,废话不多说直接上代码

依赖

<dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.drools</groupId>
      <artifactId>drools-core</artifactId>
      <version>7.0.0.Final</version>
    </dependency>
    <dependency>
      <groupId>org.drools</groupId>
      <artifactId>drools-compiler</artifactId>
      <version>7.0.0.Final</version>
    </dependency>
    <dependency>
      <groupId>org.drools</groupId>
      <artifactId>drools-decisiontables</artifactId>
      <version>7.0.0.Final</version>
    </dependency>
    <dependency>
      <groupId>org.drools</groupId>
      <artifactId>drools-templates</artifactId>
      <version>7.0.0.Final</version>
    </dependency>

    <dependency>
      <groupId>org.kie</groupId>
      <artifactId>kie-api</artifactId>
      <version>7.0.0.Final</version>
    </dependency>

    <!-- lombok -->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.16.20</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>3.0.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.9</version>
    </dependency>

  </dependencies>

启动类

import org.kie.internal.utils.KieHelper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class WebApp {

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

    @Bean
    public KieHelper kieHelper() {

        return new KieHelper();

    }
}

controller



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by Ares on 2018/6/23.
 */
@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    private DroolsServiceImpl droolsService;

    @GetMapping("/showRults/{state}")
    public String showRults(@PathVariable("state")  String state) {
        return droolsService.fireRule(Integer.valueOf(state));
    }

    @GetMapping("/generateRule")
    public String generateRule() {
        return droolsService.generateRule();
    }

}

service

import com.zf.drools.domain.Account;
import com.zf.drools.domain.Message;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.drools.decisiontable.InputType;
import org.drools.decisiontable.SpreadsheetCompiler;
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.Results;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.Collection;

/**
 * Created by Ares on 2018/6/23.
 */
@Service("droolsService")
public class DroolsServiceImpl  {
    @Autowired
    private KieHelper kieHelper;

    private  KieBase build ;

    public String fireRule(int state) {
        if(build == null)
              build = kieHelper.getKieContainer().getKieBase();
        // load up the knowledge base
   //     KieServices ks = KieServices.Factory.get();
    //    KieContainer kContainer = ks.getKieClasspathContainer();

//
//        KieSession kSession = kContainer.newKieSession("ksession-rules");
        KieSession kSession = build.newKieSession();
        // go !
        Message message = new Message();
        message.setMessage("Hello World");
        message.setStatus(state);
        kSession.insert(message);//插入
        Account account = new Account();
        account.setCount(15);
        kSession.insert(account);//插入
        kSession.fireAllRules();//执行规则
        kSession.dispose();
        return account.getPrice() + "";
    }

    public String generateRule() {
        // load up the knowledge base

        try {
            String fs = readXlsDrl("fs", "D:\\hywork\\scalatojava\\src\\main\\resources\\test.xls");
            kieHelper.addContent(fs, ResourceType.DRL);
//            FileWriter fileWriter = new FileWriter("D:\\hywork\\scalatojava\\src\\main\\resources\\rules\\test.drl");
//            fileWriter.write(fs);
//            fileWriter.close();
            KieBase build = kieHelper.build();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        }
        return "";
    }

    public String fireRule() {
        // load up the knowledge base
        String rules = "";
//        Rules ru = rulesDao.getById(id);
//        if (ru != null && ru.getRules() != null) {
//            rules = ru.getRules();
//        }

        KieServices kieServices = KieServices.Factory.get();
        KieFileSystem kfs = kieServices.newKieFileSystem();
        kfs.write("src/main/resources/rules/rules.drl", rules.getBytes());
        KieBuilder kieBuilder = kieServices.newKieBuilder(kfs).buildAll();
        Results results = kieBuilder.getResults();
        if (results.hasMessages(org.kie.api.builder.Message.Level.ERROR)) {
            System.out.println(results.getMessages());
            throw new IllegalStateException("### errors ###");
        }
        KieContainer kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());
        KieBase kieBase = kieContainer.getKieBase();
        KieSession ksession = kieBase.newKieSession();

        Message message = new Message();
        message.setStatus(0);
        ksession.insert(message);
        ksession.fireAllRules();

        return message.getMessage();
    }

    private String readXlsDrl(String type, String path) throws IOException, InvalidFormatException {
        InputStream is = null;
        if("cp".equals(type)) {
            is = this.getClass().getClassLoader().getResourceAsStream(path);
        }else if("fs".equals(type)) {
            try {
                is = new FileInputStream(path);
            } catch (FileNotFoundException e) {

                throw new RuntimeException("文件读取异常", e);
            }
        }
        SpreadsheetCompiler compiler = new SpreadsheetCompiler();
        String drl = compiler.compile(is, InputType.XLS);
        System.out.println(drl);
        return drl;
    }
}

决策表无法上传 只能截图了

 运行输出规则

package com.galaxyyao.springbootdroolstest1;
//generated from Decision Table
import com.zf.drools.domain.Account;
// rule values at B9, header at B4
rule "Account_9"
    when
        a:Account(count < 30)
    then
        a.setPrice(18.5);
    update(a);
end

// rule values at B10, header at B4
rule "Account_10"
    when
        a:Account(count > 30)
    then
        a.setPrice(15.5);
    update(a);
end

标签:drools,JAVA,String,决策表,springframework,org,import,kie
来源: https://blog.csdn.net/weixin_42710740/article/details/121945297