Drools 之 drl引擎 简单使用

 

 

 

 

 


package benx;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.drools.RuleBase;
import org.drools.RuleBaseFactory;
import org.drools.WorkingMemory;
import org.drools.compiler.DroolsParserException;
import org.drools.compiler.PackageBuilder;
import org.drools.rule.Package;

public class DroolsTest {

	private RuleBase rules;

	/**
	 * @param args
	 * @throws IOException
	 * @throws DroolsParserException
	 */
	public static void main(String[] args) throws DroolsParserException,
			IOException {
		DroolsTest rule = new DroolsTest();
		rule.init("benx.drl");

		Person per = new Person("benx", "27");

		List list = new ArrayList();
		list.add(per);
		rule.executeRules(list, null);

		System.out.println(per.getName());

	}

	/**
	 * 初始化规则引擎
	 * 
	 * @param rulesFile
	 * @throws DroolsParserException
	 * @throws IOException
	 */
	public void init(String rulesFile) throws DroolsParserException,
			IOException {
		Reader source1 = new InputStreamReader(this.getClass()
				.getResourceAsStream("/" + rulesFile));

		PackageBuilder builder = new PackageBuilder();

		/**
		 * 可以加载多个drl,执行时会遍历多个drl 等同于一个drl包含了多个drl内容
		 */
		builder.addPackageFromDrl(source1);

		Package pkg = builder.getPackage();

		rules = RuleBaseFactory.newRuleBase();
		rules.addPackage(pkg);
	}

	/**
	 * 
	 * @param obs
	 */
	public void executeRules(List obs, Map map) {
		WorkingMemory workingMemory = rules.newStatefulSession();
		if (obs != null) {
			for (Object ob : obs) {
				workingMemory.insert(ob);
			}
		}

		if (map != null) {
			for (String key : map.keySet()) {
				workingMemory.setGlobal(key, map.get(key));
			}
		}

		workingMemory.fireAllRules();
	}

}
 
  

 

 

package benx;

public class Person {
	
	private String name;
	
	private String age;

	
	public Person() {
		super();
	}

	public Person(String name, String age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

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

	public String getAge() {
		return age;
	}

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

}
 

 


package demo;
 
import benx.Person;

//规则名称,一个drl里面的规则名称必须是唯一
rule "rule 1"
//salience为优先级,数字越大就越优先执行
salience 1
//当规则在推论中对fact进行修改后,可能会导致该规则的重新激活,引起递归。设置no-loop为true可以阻止该规则被再次激活
no-loop true
//在同名activation-group中的规则将以互斥的方式激发。这个意思时在这个组中第一条被
//激发的规则将取消其它规则的激发,即使它们已经在激发队列中。Activation-group属性
//可以是任何字符,只要所有你需要放在同一个组中的规则中的activation-group属性是相
//同的即可
activation-group "find person"


//执行的条件
when
	person : Person( name == "benx")

//条件达到后执行
then		
    System.out.println("rule 1");
    person.setName("xiongjinAAA");
end




rule "rule 2"
salience 2
no-loop true
activation-group "find person"
when
	person : Person( name == "benx")
then		
    System.out.println("rule 1");
    person.setName("xiongjinAAA");
end


 

你可能感兴趣的:(java)