1. 程式人生 > >規則引擎Drools 6.4.0.Final

規則引擎Drools 6.4.0.Final

java實現規則引擎:
原理不多說,自己查閱資料吧;

搭建環境: maven spring (今天上圖 spring框架下搭建規則引擎);

1: maven 依賴;

<dependency>
            <groupId>org.kie</groupId>
            <artifactId>kie-api</artifactId>
            <version>${drools-version}</version>
        </dependency
>
<dependency> <groupId>org.kie</groupId> <artifactId>kie-internal</artifactId> <version>${drools-version}</version> </dependency> <dependency> <groupId>org.drools</groupId
>
<artifactId>drools-core</artifactId> <version>${drools-version}</version> </dependency> <dependency> <groupId>org.drools</groupId> <artifactId>drools-compiler</artifactId> <version
>
${drools-version}</version> </dependency> <dependency> <groupId>org.kie</groupId> <artifactId>kie-spring</artifactId> <version>${drools-version}</version> </dependency>

2 person.drl
一看就就明白,當 條件滿足時執行then裡面的條件語句

package com.sdingba.Drools.demo1;
import com.sdingba.Drools.demo1.person;

rule showdemo
when
    $person : person(age>3)
then
    $person.toString("xxxx");
end

3 person.java

package com.sdingba.Drools.demo1;

/**
 * Created by su on 16-10-27.
 */
public class person {
    private String name;
    private int age;
    private String comment;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public void toString(String s) {
        System.out.println(" id demo :  "+s);
    }
}

4,test.java

package com.sdingba.Drools.demo1;

import com.huitui.extend.entry.ActiveData;
import com.sdingba.SpringTestRoot;
import org.junit.Test;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.AgendaFilter;
import org.kie.api.runtime.rule.Match;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * Created by su on 16-10-27.
 */
public class demoTest extends SpringTestRoot {
    @Resource
    private KieSession kieSession;

    private static final Logger LOGGER = LoggerFactory.getLogger(demoTest.class);

    @Test
    public void testRules() {
        System.out.println("----start-----");
        person person = new person();
        person.setAge(6);
        kieSession.insert(person);
        kieSession.fireAllRules(new AgendaFilter() {
            @Override
            public boolean accept(Match match) {
                return match.getRule().getName().equals("showdemo");
            }
        });

        System.out.println(person.getName());
          System.out.println("----end-----");
    }

    @Test
    public void testTimeStamp() {
        LOGGER.info("ts={}", System.currentTimeMillis());
    }
}

配置核心類:
DroolsConfig

@Configurable
@Service
public class DroolsConfig implements InitializingBean {

    private Resource[] listRules() throws IOException {
        PathMatchingResourcePatternResolver pmrs = new PathMatchingResourcePatternResolver();
        return pmrs.getResources("classpath*:**/p*.drl");
    }

    private KieContainer loadKieContainer() throws IOException {
        KieServices kieService = KieServices.Factory.get();
        final KieRepository kieRepository = kieService.getRepository();
        kieRepository.addKieModule(kieRepository::getDefaultReleaseId);
        KieFileSystem kfs = kieService.newKieFileSystem();
        Resource[] files = listRules();

        for (Resource file : files) {
            String myString = IOUtils.toString(file.getInputStream(), "UTF-8");

//            InputStream inputStream = new ByteArrayInputStream(s.getBytes());
            String path = "src/main/resources/xxx.drl";
            kfs.write(path, myString );
        }

        KieBuilder kieBuilder = kieService.newKieBuilder(kfs);
        kieBuilder.buildAll(); // kieModule is automatically deployed to KieRepository if successfully built.
        return kieService.newKieContainer(kieRepository.getDefaultReleaseId());

    }

    @Bean
    @ConditionalOnMissingBean(KieSession.class)
    public KieSession kieSession1() throws IOException {
        return loadKieContainer().newKieSession();
    }

    @Bean
    public KieBase kieBase() throws IOException {
        return loadKieContainer().getKieBase();
    }
    @Override
    public void afterPropertiesSet() throws Exception {
//        System.out.println(" end -----");
    }
}

以上是程式碼,
注意事項:
1 pmrs.getResources(“classpath*:*/p.drl”); 這個注意;一定要是resource檔案下的(或者資源目錄下的).
2,kfs.write(path, myString );中的path可以是任意的xxx.drl
3,spring 框架的環境一定要對,可以不繼承InitializingBean
4,上面測試類繼承關係如下 :

SpringTestRoot.java

package com.sdingba;

import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

/**
 * Created by su on 16-10-27.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(ServerLauncher.class)
@WebAppConfiguration
public class SpringTestRoot {
    protected static final Logger LOGGER = LoggerFactory.getLogger(SpringTestRoot.class);
}

ServerLauncher.java

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

}

測試的依賴:

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

無spring的:

        PathMatchingResourcePatternResolver pmrs = new PathMatchingResourcePatternResolver();
        Resource[] resources = pmrs.getResources("classpath*:**/p*.drl");

        KieServices kieService = KieServices.Factory.get();
        final KieRepository kieRepository = kieService.getRepository();
        kieRepository.addKieModule(kieRepository::getDefaultReleaseId);
        KieFileSystem kfs = kieService.newKieFileSystem();

        for (Resource file : resources) {
            String myString = IOUtils.toString(file.getInputStream(), "UTF-8");
            String path = "src/main/resources/" + file.getFilename();
            kfs.write(path, myString);
            System.out.println();
        }

        KieBuilder kieBuilder = kieService.newKieBuilder(kfs);
        kieBuilder.buildAll();
        KieContainer kieContainer = kieService.newKieContainer(kieRepository.getDefaultReleaseId());



        KieSession kieSession = kieContainer.newKieSession();

        person person = new person();
        person.setAge(6);
        kieSession.insert(person);
        kieSession.fireAllRules();
        System.out.println(person.getName());