找到任何规则时,如何在Drools中停止规则执行。规则是这样的:
rule "Restore zxGponOltSDi IVR"
when
$log: LogDTO (
nameEvent in (
"zxGponOltSDiRestore"
)
)
then
insert (
new RestoreEventAlarmDTO(
$log.getNameEvent(),
new String[] {"zxGponOltSDi"},
$log.getIp(),
new Date(),
$log.getInterFace()
)
);
//Add something for stopping execution
end
在drl文件中,有34条规则,执行时间太长。当找到任何规则时,我需要执行最终确定。
package com.claro.cpymes.rule;
import java.io.FileInputStream;
import java.util.Collection;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.*;
import org.drools.runtime.StatefulKnowledgeSession;
import com.claro.cpymes.dto.*;
import com.claro.cpymes.util.Constant;
public class RestoreEvent {
private static Logger LOGGER = LogManager.getLogger(RestoreEvent.class.getName());
KnowledgeBase kbase;
StatefulKnowledgeSession ksession;
public void initialize() throws Exception {
kbase = RestoreEvent.readKnowledgeBase(Constant.PATH_DRL_FILE_RESTORE);
ksession = kbase.newStatefulKnowledgeSession();
}
public RestoreEventAlarmDTO restoreEvent(LogDTO log) {
ksession.insert(log);
ksession.fireAllRules();
Collection<Object> listEventRestore = ksession.getObjects();
RestoreEventAlarmDTO restoreEventAlarm = null;
for (Object obj : listEventRestore) {
if (obj instanceof RestoreEventAlarmDTO) {
restoreEventAlarm = ((RestoreEventAlarmDTO) obj);
ksession.retract(ksession.getFactHandle(obj));
break;
}
}
return restoreEventAlarm;
}
private static KnowledgeBase readKnowledgeBase(String drlFile) throws Exception {
FileInputStream fis = new FileInputStream(drlFile);
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add(ResourceFactory.newInputStreamResource(fis), ResourceType.DRL);
KnowledgeBuilderErrors errors = kbuilder.getErrors();
if (errors.size() > 0) {
for (KnowledgeBuilderError error : errors) {
LOGGER.info(error);
}
throw new IllegalArgumentException("Could not parse knowledge.");
}
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
return kbase;
}
}
答案 0 :(得分:0)
非常简单:
ksession.fireAllRules( 1 );
在第一个规则触发后返回。