public class MyDroolsTest {
public static void main(String[] agrs ){
Order order = new Order();
order.setId("01020");
order.setName("京东订单");
order.setPrice(5001);
order.setArea("beijing");
User user = new User();
user.setUserId("guohui");
user.setUserName("guohui");
StatefulKnowledgeSession ksession = null;
try {
// load up the knowledge base
KnowledgeBase kbase = DroolsTools.readKnowledgeBase("OrderDrl.drl");
ksession = kbase.newStatefulKnowledgeSession();
KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");
// go !
ksession.insert(order);
ksession.insert(user);
ksession.fireAllRules();
//ksession.
logger.close();
} catch (Throwable t) {
t.printStackTrace();
}finally{
//释放资源
ksession.dispose();
}
}
}
domain
Order:
public class Order {
private String id;
private String name;
private int price;
private String area;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
}
User:
public class User {
private String userId;
private String userName;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
Droolstools
public class DroolsTools {
/**
* 读取解析DRL文件
* @param DrlName
* @return
* @throws Exception
*/
public static KnowledgeBase readKnowledgeBase(String DrlName) throws Exception {
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add(ResourceFactory.newClassPathResource(DrlName), ResourceType.DRL);
KnowledgeBuilderErrors errors = kbuilder.getErrors();
if (errors.size() > 0) {
for (KnowledgeBuilderError error: errors) {
System.err.println(error);
}
throw new IllegalArgumentException("Could not parse knowledge.");
}
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
return kbase;
}
}
orderDrl.drl
package com.sample
import com.sample.my.test.Order;
import com.sample.my.test.User;
rule "first"
when
Order(area == "beijing",price > 5000,str : name) and User(userId == "guohui",$name : userName)
then
System.out.println("操作人"+$name+"属于北京的订单大于5000经理审批====================="+str);
end
rule "second"
when
Order(area == "shanghai",price < 5000,str : name) and User(userId == "guohui",$name : userName)
then
System.out.println("操作人"+$name+"不属于北京的订单小于5000主管审批==========================="+str);
end
分享到:
2011-06-02 15:26
浏览 871
评论