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

Drools动态构造规则内容

程序员文章站 2022-05-28 11:15:59
...
package com.sample;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

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.definition.type.FactType;
import org.drools.event.DebugWorkingMemoryEventListener;
import org.drools.rule.Package;

public class DynamicRules {

public static String buildRuleSource(){
//完整的规则内容如下:
/*
package com.sample
declare People
id:String
name:String
returnContent:String
end

rule "rule2"
when
$people : People( id == "001")
then
System.out.println( $people.getName());
end
*/

StringBuffer sb = new StringBuffer();
sb.append("package com.sample");
sb.append("\r\n");
sb.append("declare People");
sb.append("\r\n");
sb.append("id:String");
sb.append("\r\n");
sb.append("name:String");
sb.append("\r\n");
sb.append("end");
sb.append("\r\n");
sb.append("rule \"rule2\"");
sb.append("\r\n");
sb.append("when");
sb.append("\r\n");
sb.append("$People : People( id == \"001\")");
sb.append("\r\n");
sb.append("then");
sb.append("\r\n");
sb.append("System.out.println( $People.getName());");
sb.append("\r\n");
sb.append("end");

//System.out.println(sb.toString());
return sb.toString();
}

public static void executeRules(Reader source) throws DroolsParserException, IOException{
try {

//创建PackageBuilder
PackageBuilder packgebuilder = new PackageBuilder();

//解析编译规则包,可加入多个source
packgebuilder.addPackageFromDrl(source);

//获得已经编译的规则包
Package pkg = packgebuilder.getPackage();

//创建一个规则集
RuleBase ruleBase = RuleBaseFactory.newRuleBase();

//加载已规则包
ruleBase.addPackage(pkg);

//获得规则中需要使用的事实对象,方式:包名.事实名
FactType factType = ruleBase.getFactType("com.sample.People");

//创建一个事实实例
Object factPeople1 = factType.newInstance();

//给事实属性赋值
factType.set(factPeople1, "id", "001");
factType.set(factPeople1, "name", "tom");

//执行规则。方法1,使用StatefulSession,一次只能插入一个事实
//WorkingMemory workingMemory = ruleBase.newStatefulSession();
//workingMemory.addEventListener(new DebugWorkingMemoryEventListener());
//workingMemory.insert(factPeople1);
//workingMemory.fireAllRules();

//执行规则。方法2,使用StatelessSession执行规则
//可传入Collect/Object[]/Object
ruleBase.newStatelessSession().execute(new Object[] {factPeople1});

} catch (Throwable t) {
t.printStackTrace();
}
}

/**
* @param args
*/
public static void main(String[] args) {

//构造规则内容字符串,此处可换成从数据库读取规则的各个部分,包括事实、包名称、函数、import内容构造一个完整的规则文件
String s = buildRuleSource();
//转换成Reader
StringReader source = new StringReader(s);
try{
executeRules(source);
}
catch(Throwable t){
t.printStackTrace();
}
}
}