使用Struts 2开发应用04:程序概要分析

文章翻译自Struts 2官方文档

程序概要分析软件寻找程序执行过程中的瓶颈。除了IDE提供的概要分析服务和独立的分析软件之外,框架提供了程序概要分析的内部支持。

程序概要分析的概貌

Struts2程序概要分析的概貌包括下面的内容:

  • ActionContextCleanUp
  • FreemarkerPageFilter
  • DispatcherFilter
    • Dispatcher
      • creation of DefaultActionProxy
        • creation of DefaultActionInvocation
          • creation of Action
      • execution of DefaultActionProxy
        • invocation of DefaultActionInvocation
          • invocation of Interceptors
          • invocation of Action
          • invocation of PreResultListener
          • invocation of Result

使用程序概要分析

为了使用程序概要分析,首先设法确保你的action已经使用了profiling拦截器,像下面这样:

<action ... >   
   ... 
   <interceptor-ref name="profiling"> 
       <param name="profilingKey">profiling</param> 
   </interceptor-ref> 
   ... 
</action> 

然后用下面的方法之一使用程序概要分析:

通过系统属性启动

-Dxwork.profile.activate=true

这可以在容器的启动脚本里完成,例如在catalina.sh的CATALINA_OPTS(tomcat)或者使用‘java -Dxwork.profile.activate=true’(jetty)。

通过代码启动

UtilTimerStack.setActivate(true);

这可以在静态块中完成,在Spring bean中使用lazy-init=‘false’,在Servlet中使用带数字值的init-on-startup,在过滤器或监听器的init方法中等等。

通过参数启动

http://host:port/context/namespace/someAction.action?profiling=true 

改变启动参数的名字

设置profiling拦截器的profilingKey属性为期望的名字:

<action ... >   
   ... 
   <interceptor-ref name="profiling"> 
       <param name="profilingKey">profiling</param> 
   </interceptor-ref> 
   ... 
</action> 

通过参数启动程序概要分析要求struts.devMode的值为true

过滤程序概要分析信息

通过设置下面的系统属性你可以过滤概要分析的日志:

-Dxwork.profile.mintime=10000

使用xwork.profile.mintime属性,你可以仅输出执行时间超过定义在xwork.profile.mintime系统属性中的时间的概要分析信息。若果没有定义这个属性,这个属性的值将假设为0,所以所有的概要分析信息都会输出。

编写程序概要分析代码

在自己的web应用中你也可以扩展Struts2提供的概要分析功能。

使用UtilTimerStack的push和pop

String logMessage = "Log message"; 
UtilTimerStack.push(logMessage); 
try { 
    // do some code 
} finally { 
    UtilTimerStack.pop(logMessage); // this needs to be the same text as above 
} 

使用UtilTimerStack的ProfileBlock模板

String result = UtilTimerStack.profile("purchaseItem: ",  
      new UtilTimerStack.ProfilingBlock<String>() { 
           public String doProfiling() { 
              // do some code 
              return "Ok"; 
           } 
      }); 

程序概要分析日志文件

概要分析的结果使用commons-logging下的名为com.opensymphony.xwork2.util.profiling.UtilTimerStack的logger输出。依赖底层的日志实现方式,比如说是Log4j,你可以指示日志输出到不同的文件,用邮件的方式发给某人或者把它存储到数据库中。

猜你喜欢

转载自a2429854489.iteye.com/blog/2285555