您的位置:首页 > 运维架构 > Apache

职责链实现的apache.chain使用

2015-06-19 17:34 573 查看
其实职责链在老早就使用过了,以前在HW给Vodafone做金融项目的时候,使用职责链完成交易步骤,那时觉得这东西真好用,可以直接通过配置决定业务流程,现在终于有机会实践一下。

项目地址:http://commons.apache.org/proper/commons-chain/

这种设计模式本身的实现是非常容易的,可以简单单做是一组IF条件的集合,符合条件的继续传递;不符合条件的终止运行。chain代表了一条运行逻辑,就如同一条项链,我们的业务逻辑就如同是珍珠,并且都实现了同样的compute接口。apache的实现,是通过将数据封装到上下文(context)中,而且该上下文就是串起这些珍珠的金线。

下面是自己写的一段例子:

 链的组织,也可以通过配置xml文件来实现,用在spring框架中非常合适。



/**
*职责链的组织类,负责构造整个链
*/
publicclassRootCauseChainextendsChainBase
{
/**
*通过此方法增减生效的分析器
*/
publicRootCauseChain()
{
addCommand(newDataRootCauseAnalyzer());
//addCommand(newEnvRootCauseAnalyzer());
//addCommand(newPifRootCauseAnalyzer());
//addCommand(newTaskRootCauseAnalyzer());
}
}

具体的业务:  

/**
*实现了command接口,数据均通过context组织
*/
publicclassDataRootCauseAnalyzerimplementsCommand
{
privateDataQueryServicedqService=newDataQueryService();

privatestaticfinalStringROOT_CAUSE_FORMAT="indicatorvalueisabnormal:check?formoreinformation";

@SuppressWarnings("unchecked")
@Override
publicbooleanexecute(Contextarg0)throwsException
{
booleanres=false;

Log.info(RootCauseConstant.MODULE_CODE,"0000",
"begintoexecuteDataRootCauseAnalyzer.execute");

List<DataPoint>exceptionDataPoints=(List<DataPoint>)arg0.get("expData");
ExceptionRuleexceptionRule=(ExceptionRule)arg0.get("rule");

List<RootCause>result=newArrayList<RootCause>();

if(exceptionDataPoints!=null&&!exceptionDataPoints.isEmpty())
{
for(DataPointdataPoint:exceptionDataPoints)
{
List<RootCause>rootCauseList=generateRootCause(dataPoint,exceptionRule);

result.addAll(rootCauseList);
}
}

//如果分析出了根因,则结束分析流程
if(result!=null&&!result.isEmpty())
{
arg0.put("result",result);

res=true;
}

//没有分析出根因,交到下一个分析器进行分析
returnres;
}

/**
*生成具体的异常信息
*
*@paramexceptionPoint
*异常数据点
*@paramrule
*异常规则
*@return查询上下级关系
*/
privateList<RootCause>generateRootCause(DataPointexceptionPoint,ExceptionRulerule)
{
List<RootCause>rclist=newArrayList<RootCause>();

returnrclist;
}
}


  调用:

publicclassRootCauseService
{
/**
*分析异常点的根因
*
*@parampoints
*异常数据点
*@paramrule
*异常数据发现规则
*@return异常数据点及根因
*/
@SuppressWarnings("unchecked")
publicList<RootCause>getRootCause(List<DataPoint>points,ExceptionRulerule)
{
Log.info(RootCauseConstant.MODULE_CODE,"0000","begintoexecutegetRootCause,points="
+points+",rule="+rule);

List<RootCause>result=newArrayList<RootCause>();

try
{
Commandcommand=newRootCauseChain();
ContextBasectx=newContextBase();

ctx.put("expData",points);
ctx.put("rule",rule);

command.execute(ctx);
result=(List<RootCause>)ctx.get("result");
}
catch(Exceptione)
{
Log.error(RootCauseConstant.MODULE_CODE,"0000",
"executeanalysisRootCauseByCommandChainexception.",e);
}

Log.info(RootCauseConstant.MODULE_CODE,"0000","executegetRootCausefinished,result="
+result);

returnresult;
}
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: