通过debug跟踪Drools的执行源码,实现执行规则的记录(输出)功能。
在ksession.fireAllRules(); 进入类StatefulKnowledgeSessionImpl.fireAllRules()中
类StatefulKnowledgeSessionImpl主要涉及的成员变量及方法:
public ReteooWorkingMemory session; public int fireAllRules() { return this.session.fireAllRules(); }
其中ReteooWorkingMemory 继承自AbstractWorkingMemory
故上面return 调用的是AbstractWorkingMemory的fireAllRules()方法
类AbstractWorkingMemory主要涉及的成员变量及方法:
protected InternalAgenda agenda; public synchronized int fireAllRules() throws FactException { return fireAllRules( null, -1); } public synchronized int fireAllRules(final AgendaFilter agendaFilter, int fireLimit) throws FactException { if ( isSequential() ) { for ( Iterator it = this.liaPropagations.iterator(); it.hasNext(); ) { ((LIANodePropagation) it.next()).doPropagation( this ); } } // do we need to call this in advance? executeQueuedActions(); int fireCount = 0; if ( this.firing.compareAndSet( false, true ) ) { try { fireCount = this.agenda.fireAllRules( agendaFilter,fireLimit); } finally { this.firing.set( false ); } } return fireCount; }
调用了agenda.fireAllRules()方法,而DefaultAgenda实现了InternalAgenda接口
类DefaultAgenda所涉及的方法:
public int fireAllRules(AgendaFilter agendaFilter, int fireLimit) { this.halt.set( false ); int fireCount = 0; while ( continueFiring( fireLimit ) &&fireNextItem( agendaFilter )) { fireCount++; fireLimit = updateFireLimit( fireLimit ); this.workingMemory.executeQueuedActions(); } if ( this.focusStack.size()==1 && getMainAgendaGroup().isEmpty() ) { getMainAgendaGroup().setActive( false ); } return fireCount; } 其中fireNextItem方法如下: public boolean fireNextItem(final AgendaFilter filter) throws ConsequenceException { boolean tryagain, result; do { tryagain = result = false; final InternalAgendaGroup group = (InternalAgendaGroup) getNextFocus(); // if there is a group with focus if ( group != null ) { final AgendaItem item = (AgendaItem) group.getNext(); // if there is an item to fire from that group if ( item != null ) { // if that item is allowed to fire if ( filter == null || filter.accept( item ) ) { // fire it System.out.println(item.getRule().getName()); //输出执行的规则名 fireActivation( item ); result = true; } else { // otherwise cancel it and try the next final EventSupport eventsupport = (EventSupport) this.workingMemory; eventsupport.getAgendaEventSupport().fireActivationCancelled( item, this.workingMemory, ActivationCancelledCause.FILTER ); tryagain = true; } } } } while ( tryagain ); return result; }
使用ystem.out.println(item.getRule().getName())输出执行到的规则名