drools决策表及实例

drools决策表及实例

决策表

  1. 决策表又称判断表,适用于描述处理判断条件较多,各条件又相互组合、有多种决策方案的情况。精确而简洁描述复杂逻辑的方式,将多个条件与这些条件满足后需要执行动作相对应。

  2. 决策表语法

关键字 说明
RuleSet 等价于drl文件的package,必须,如果没有设置对应的值默认为rule_table
Sequential 布尔类型,true表示规则按照表格自上而下顺序执行,false表示乱序,可选
Import 等价于drl文件中的import,如果引入多个类,则类之间使用逗号分隔,可选
Variables 等价于drl文件中的global,定义全局变量,多个全局变量则使用逗号分隔,可选
RuleTable 指示后面会有一批rule,RuleTable的名称会作为以后生成rule的前缀,必须
CONDITION 规则条件关键字,相当于drl文件中的when。下面两行则表示LHS部分,第三行则为注释行,从第四行开始每一行表示一条规则,每个规则表至少有一个
ACTION 规则结果关键字,相当于drl文件中的then,每个规则表至少有一个
NO-LOOP 相当于drl文件中的no-loop,可选
AGENDA-GROUP 相当于drl文件中的agenda-group,可选

在决策表中经常使用到的占位符,语法是使用$加数字,用于替换每条规则中设置的具体值。

决策表实例

  1. 创建maven工程drools_demo,并设置pom.xml文件
xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.lxx</groupId>
    <artifactId>drools_demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.12</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.drools</groupId>
            <artifactId>drools-compiler</artifactId>
            <version>7.10.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.drools</groupId>
            <artifactId>drools-templates</artifactId>
            <version>7.10.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.kie</groupId>
            <artifactId>kie-spring</artifactId>
            <version>7.10.0.Final</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-core</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-beans</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-tx</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <!--修改maven默认的JDK设置-->
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
  1. 创建application.yaml配置spring应用
yaml 复制代码
server:
  port: 8088

spring:
  application:
    name: drools_demo
  1. 创建事实对象Person.java
java 复制代码
package org.lxx.drools.entity;

import lombok.Data;

@Data
public class Person {

    private int age;
    private String sex;
    private double salary;

}
  1. 创建工具类解析Excel决策表KieSessionUtils.java
java 复制代码
package org.lxx.drools.utils;

import org.drools.decisiontable.InputType;
import org.drools.decisiontable.SpreadsheetCompiler;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

public class KieSessionUtils {

    private KieSessionUtils(){}

    public static String getDrl(String path) throws Exception {
        File file = new File(path);
        InputStream is = new FileInputStream(file);
        SpreadsheetCompiler compiler = new SpreadsheetCompiler();
        String drl = compiler.compile(is, InputType.XLS);
        System.out.println(drl);
        return drl;
    }

    public static KieSession createKieSessionFromDrl(String drl) throws Exception {
        KieHelper kieHelper = new KieHelper();
        kieHelper.addContent(drl, ResourceType.DRL);
        Results results = kieHelper.verify();
        if (results.hasMessages(Message.Level.WARNING, Message.Level.ERROR)) {
            List<Message> messages = results.getMessages(Message.Level.WARNING, Message.Level.ERROR);
            for (Message message : messages) {
                System.out.println("Error:" + message.getText());
            }
        }
        return kieHelper.build().newKieSession();
    }

    public static KieSession getKieSessionFromXls(String path) throws Exception {
        return createKieSessionFromDrl(getDrl(path));
    }
}
  1. 创建服务类RuleService.java
java 复制代码
package org.lxx.drools.service;

import org.kie.api.runtime.KieSession;
import org.lxx.drools.entity.Person;
import org.lxx.drools.utils.KieSessionUtils;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

@Service
public class RuleService {

    public List<String> personCheck(Person person) throws Exception {
        List<String> listRules = new ArrayList<>();
        KieSession session = KieSessionUtils.getKieSessionFromXls("C:\\Users\\asus\\IdeaProjects\\drools_demo\\src\\main\\resources\\rule.xls");
        session.getAgenda().getAgendaGroup("sign").setFocus();
        session.insert(person);
        session.setGlobal("listRules", listRules);
        session.fireAllRules();
        return listRules;
    }


}
  1. 创建控制器RuleController.java
java 复制代码
package org.lxx.drools.controller;

import org.apache.commons.collections4.CollectionUtils;
import org.lxx.drools.entity.Person;
import org.lxx.drools.service.RuleService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/rule/")
public class RuleController {

    @Resource
    private RuleService ruleService;

    @RequestMapping("personCheck")
    public Map personCheck() {
        Map map = new HashMap();
        Person person = new Person();
        person.setAge(24);
        person.setSalary(15000);
        person.setSex("男");
        try {
            List<String> list = ruleService.personCheck(person);
            if (CollectionUtils.isNotEmpty(list)) {
                map.put("checkResult", false);
                map.put("msg", "失败");
                map.put("detail", list);
            } else {
                map.put("checkResult", true);
                map.put("msg", "成功");
            }
            return map;
        } catch (Exception e) {
            map.put("checkResult", false);
            map.put("msg", "未知错误");
            return map;
        }
    }

}
相关推荐
代码之光_198020 分钟前
保障性住房管理:SpringBoot技术优势分析
java·spring boot·后端
ajsbxi26 分钟前
苍穹外卖学习记录
java·笔记·后端·学习·nginx·spring·servlet
StayInLove1 小时前
G1垃圾回收器日志详解
java·开发语言
对许1 小时前
SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder“
java·log4j
无尽的大道1 小时前
Java字符串深度解析:String的实现、常量池与性能优化
java·开发语言·性能优化
小鑫记得努力1 小时前
Java类和对象(下篇)
java
binishuaio1 小时前
Java 第11天 (git版本控制器基础用法)
java·开发语言·git
zz.YE1 小时前
【Java SE】StringBuffer
java·开发语言
老友@1 小时前
aspose如何获取PPT放映页“切换”的“持续时间”值
java·powerpoint·aspose
wrx繁星点点1 小时前
状态模式(State Pattern)详解
java·开发语言·ui·设计模式·状态模式