清单 2 中使用了 LoggingStopWatch 类,其 stop() 方法只是将执行时间数据通过 System.err.println() 输 出。若与 Log4j 框架集成,则需要使用 LoggingStopWatch 的子类 Log4JStopWatch, 目前 Perf4j 还支持 Apache Commons Logging、java.util.logginLogback,对应使用 CommonsLogStopWatch、 JavaLogStopWatch、Slf4JStopWatch。
以 Log4j 为例,在 Log4j.xml 中要为 Log4JStopWatch 加入异步输出源 AsyncCoalescingStatisticsappender。 尽量使专用于 Perf4JAppender 的 fileAppender,从而保证记录的性能数据输出到独立的日志文件中。
清单 3.Log4j 配置文件
class="org.perf4j.log4j.AsyncCoalescingStatisticSAPpender">
清单 3 中设置了 TimeSlice 为 10 秒, Perf4jAppender 则以 10 秒为采样间隔,统计后按时 间分组输出。清单 4 中是一个采样单位的数据。
清单 4. 日志输出数据示例
Performance Statistics
2012-07-02 21:45:30 - 2012-07-02 21:45:40
Tag Avg(ms) Min Max Std Dev Count
LogicalBlock1 1997.0 1997 1997 0.0 1
LogicalBlock2 499.0 499 499 0.0 1
对方法计时
若要避免 Perf4j 与系统的紧耦合,不在程序中加入额外的第三方代码,还可以借助面向方面编程(AOP),通过简单的 配置在运行中动态地对指定的方法计时。Perf4j 对常用的 AOP 工具如 AspectJ 及 Spring AOP 均提供了良好支持 . 在此 主要介绍下 Per4j 与后者集成的配置方式。
首先确保工程中已有如图 1 中的 Jar 包:
图 1. 必需引入的 Lib
其次在 Spring 的配置文件(一般是 applicationContext.xml 或 spring-config.xml)中加入 及申 明 org.perf4j.log4j.aop.TimingAspect 做为 。具体配置参考清单 5:
清单 5.Spring AOP 申明
expression="execution(* cn.test.perf4j.example..*.*(..)) and @annotation(profiled)"/>
其中切入点 的表达式(expression)中包的作用域可以按实际需求进行修;@annotation(profiled) 会把 @org.perf4j.aop.Profiled 做为参数传给 TimingAspect,在此则不能删除此条件。当然还可以采用 替换 复杂的配置,在 org.perf4j.log4j.aop.TimingAspect 的父类 ProfiledTimingAspect 中已用注解定义过全局的切入点。 具有更大的灵活性,可以任意设置监测的范 围,建议产品环境使用。
运行时如果遇到如下异常:
“The matching wildcard is strict, but no declaration can be found for element 'aop:config'”
说明之前没有设置过 AOP 的命名空间,在 xsi:schemaLocation 最后加相对应版本的 URI 即可。
清单 6. 加入 spring-aop-x.x.xsd 的 URI
¥299.00
¥29.00
¥399.00
¥498.00