Drools规则引擎(四):SpringBoot整合

一:pom.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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springboot-drools</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-drools</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.drools</groupId>
            <artifactId>drools-compiler</artifactId>
            <version>7.37.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.drools</groupId>
            <artifactId>drools-mvel</artifactId>
            <version>7.73.0.Final</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

二:config

package com.example.springbootdrools.config;

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.internal.io.ResourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;
/**
 * 规则引擎配置类
 */
@Configuration
public class DroolsConfig {
    //指定规则文件存放的目录
    private static final String RULES_PATH = "rules/";
    private final KieServices kieServices = KieServices.Factory.get();

    @Bean
    public KieFileSystem kieFileSystem() throws IOException {
    	// 设置日期格式
    	System.setProperty("drools.dateformat", "yyyy-MM-dd HH:mm:ss");
        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();
            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();
    }
}

三:entity

@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Student {
    private Long id;
    private String name;
    private Integer age;
}

四:rule

src/main/resources/rules/test.drl

// 7.37.0.Final中的package的值可以随意定义
package xxx
import com.example.springbootdrools.entity.Student

rule "rule_test"
    when
        $student:Student(age > 18)
    then
        System.out.println("rule_test 触发成功 " + $student.getName());
end

五:controller

@RestController
@RequestMapping("/drools")
public class DroolsController {
	@Autowired
    private KieContainer kieContainer;

    @RequestMapping("/test")
    public void test() {
        KieSession kieSession = kieContainer.newKieSession();
        kieSession.insert(new Student(1L, "张三", 35));
        kieSession.fireAllRules();
        kieSession.dispose();
    }

	/*
		删除.drl文件,将规则文件以字符串的方式动态配置,也不需要DroolsConfig。

		Drools提供了一个工具类 KieHelper,可以将规则文件作为content内容字符串String参数加载进来。
		可以将规则文件保存到数据库中,也可以将规则文件保存到配置中心
		也可以由页面提供规则参数生成规则脚本保存到数据库中
	*/
	@RequestMapping("/test2")
    public void test2() {
        // 模拟从数据库读取规则文件内容
        String rule = "package xxx\n" +
                "import com.example.springbootdrools.entity.Student\n" +
                "\n" +
                "rule \"rule_test_str\"\n" +
                "    when\n" +
                "        $student:Student(age > 18)\n" +
                "    then\n" +
                "        System.out.println(\"rule_test_str 触发成功 \" + $student.getName());\n" +
                "end";


        // 第三步:新建会话
        KieHelper kieHelper = new KieHelper();
        kieHelper.addContent(rule, ResourceType.DRL);

        // 校验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(message.getText());
            }
            throw new IllegalStateException("drl verify error");
        }

        KieSession kieSession = kieHelper.build().newKieSession();

        // 第四步:插入事实对象
        kieSession.insert(new Student(1L, "张三", 35));
        // 第五步:执行规则引擎
        kieSession.fireAllRules();
        // 第六步:关闭session
        kieSession.dispose();
    }
}

六:test

http://localhost:8080/drools/test

在这里插入图片描述
http://localhost:8080/drools/test2
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风流 少年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值