2

我对 Drools 很陌生,并调整了我在这里找到的 Spring Boot 配置,使我能够从数据库中读取一堆规则作为字符串,而不是从应用程序文件夹中的 DRL 文件中读取它们。

当我使用下面的代码启动我的应用程序时,我使用 Spring Boot、Drools 6.5.Final、Java 1.8 得到以下异常:

引起:java.lang.RuntimeException:资源既没有源也没有目标路径。无法将其添加到捆绑包中。请在添加它之前设置资源的源或目标名称。在 org.drools.compiler.kie.builder.impl.KieFileSystemImpl.write(KieFileSystemImpl.java:95) ~[drools-compiler-6.5.0.Final .jar:6.5.0.Final]

package com.example.demo;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

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.KieModule;
import org.kie.api.builder.KieRepository;
import org.kie.api.builder.ReleaseId;
import org.kie.api.io.Resource;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DroolsDatabaseConfig {

    @Autowired
    private DataService dataService;

    @Bean
    public KieFileSystem kieFileSystem() throws IOException {
        KieFileSystem kieFileSystem = getKieServices().newKieFileSystem();
        for (Resource resource : getRulesFromDB()) {
            kieFileSystem.write(resource);
        }        
        return kieFileSystem;
    }

    private List<Resource> getRulesFromDB() throws IOException {
        List<Resource> resources = new ArrayList<Resource>();

        List<String> rules = dataService.getRulesFromDB();
        for (String rule : rules){
            Resource r = ResourceFactory.newInputStreamResource(new ByteArrayInputStream(rule.getBytes(StandardCharsets.UTF_8)));
            resources.add(r);
        }
        return resources;
    }

    @Bean
    public KieContainer kieContainer() throws IOException {
        final KieRepository kieRepository = getKieServices().getRepository();

        kieRepository.addKieModule(new KieModule() {
            public ReleaseId getReleaseId() {
                return kieRepository.getDefaultReleaseId();
            }
        });

        KieBuilder kieBuilder = getKieServices().newKieBuilder(kieFileSystem()); 
        kieBuilder.buildAll();

        return getKieServices().newKieContainer(kieRepository.getDefaultReleaseId());
    }

    private KieServices getKieServices() {
        return KieServices.Factory.get();
    }

    @Bean
    public KieBase kieBase() throws IOException {
        return kieContainer().getKieBase();
    }

    @Bean
    public KieSession kieSession() throws IOException {
        return kieContainer().newKieSession();
    }
}

关于如何解决这个问题以允许我从字符串加载规则的任何想法?

提前致谢

4

0 回答 0