欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【java】drools动态执行不同规则文件的规则

程序员文章站 2022-03-03 15:55:30
...

假设有两个规则文件,具体执行哪一个规则文件需要根据配置文件来动态确定,那么,可以通过下述的方式实现: 

package com.drools;

import java.io.File;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.Scanner;

import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.impl.KnowledgeBaseFactory;
import org.kie.api.definition.KiePackage;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.StatelessKieSession;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.io.ResourceFactory;

@SuppressWarnings("restriction")
public class Test2 {

	public static void main(String[] args) {

		try {

			Scanner in = new Scanner(System.in);
			System.out.println("请输入需要评级的分数:(输入0退出循环)");
			int data = in.nextInt();
			while (data != 0) {
				Score s = new Score(data);

				// load up the knowledge base
				KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
				String filePath = Test2.class.getClassLoader().getResource("com/drools/rules/rule1.drl").getPath();
				//String filePath = Test2.class.getClassLoader().getResource("com/drools/rules/rule1.dr2").getPath();
				File file = new File(URLDecoder.decode(filePath, "utf-8"));
				kbuilder.add(ResourceFactory.newFileResource(file), ResourceType.DRL);
				InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
				Collection<KiePackage> ss = kbuilder.getKnowledgePackages();
				kbase.addPackages(ss);
				StatelessKieSession ksession = kbase.newStatelessKieSession();
				ksession.execute(s);

				System.out.println("请输入需要评级的分数:(输入0退出循环)");
				data = in.nextInt();
			}
		} catch (Throwable t) {
			t.printStackTrace();
		}
	}

}