文章翻译自Struts 2官方文档。
程序概要分析软件寻找程序执行过程中的瓶颈。除了IDE提供的概要分析服务和独立的分析软件之外,框架提供了程序概要分析的内部支持。
程序概要分析的概貌
Struts2程序概要分析的概貌包括下面的内容:
- ActionContextCleanUp
- FreemarkerPageFilter
- DispatcherFilter
- Dispatcher
- creation of DefaultActionProxy
- creation of DefaultActionInvocation
- creation of Action
- creation of DefaultActionInvocation
- execution of DefaultActionProxy
- invocation of DefaultActionInvocation
- invocation of Interceptors
- invocation of Action
- invocation of PreResultListener
- invocation of Result
- invocation of DefaultActionInvocation
- creation of DefaultActionProxy
- Dispatcher
使用程序概要分析
为了使用程序概要分析,首先设法确保你的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,你可以指示日志输出到不同的文件,用邮件的方式发给某人或者把它存储到数据库中。