perf4j的应用

1、添加依赖
<dependency>
		  <groupId>org.perf4j</groupId>
		  <artifactId>perf4j</artifactId>
		  <version>0.9.16</version>
		</dependency>
		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
        </dependency>
        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
        </dependency>


2、创建拦截器
package cn.focus.dc.app.interceptors;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import net.paoding.rose.web.ControllerInterceptorAdapter;
import net.paoding.rose.web.Invocation;

import org.apache.commons.lang.StringUtils;
import org.perf4j.StopWatch;
import org.perf4j.aop.Profiled;
import org.perf4j.slf4j.Slf4JStopWatch;
import org.springframework.stereotype.Service;

/**
 * @author qiaowang
 * @date 2013-12-18 下午4:42:02
 */
@Service
public class Perf4jInterceptor extends ControllerInterceptorAdapter {
    
    private static final String FLAG_AT = "@";

    private static final String FLAG_AOT = ".";

    private Map<String, StopWatch> watches = new HashMap<String, StopWatch>();
    
    /**
     * <p>
     * Constructor for AccessTokenInterceptor.
     * </p>
     */
    public Perf4jInterceptor() {
        this.setPriority(100);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Class<? extends Annotation> getRequiredAnnotationClass() {
        return Profiled.class;
    }

    @Override
    public Object before(Invocation inv) {
        Method method = inv.getMethod();
        Object[] args = inv.getMethodParameters();
        Object target = inv.getControllerClass();
        
        String completeMethodName = getCompleteMethodName(target, method);
        
        //创建性能日志记录器
        StopWatch stopWatch;
        if(watches.containsKey(completeMethodName)){
            stopWatch = watches.get(completeMethodName);
            stopWatch.start();
        } else {
            stopWatch = new Slf4JStopWatch(completeMethodName, Arrays.toString(args));
            watches.put(completeMethodName, stopWatch);
        }
        return true;
    }

    /**
     * 根据目标对象与方法获取方法完整名称.
     * 
     * @author qiaowang
     * @date 2013-12-18 下午4:45:36
     * @param target 目标对象
     * @param method 方法
     * @return String 方法完整名称
     */
    private String getCompleteMethodName(Object target, Method method) {
        String className = StringUtils.EMPTY;
        if (target != null) {
            className = target.toString();
            int loc = className.indexOf(FLAG_AT);
            if (loc >= 0) {
                className = className.substring(0, loc);
            }
        }
        StringBuilder buf = new StringBuilder();
        buf.append(className).append(FLAG_AOT).append(method.getName());
        return buf.toString();
    }

    @Override
    public Object after(Invocation inv, Object instruction) throws Exception {
        Method method = inv.getMethod();
        Object target = inv.getControllerClass();
        
        String completeMethodName = getCompleteMethodName(target, method);
        
        //创建性能日志记录器
        StopWatch stopWatch;
        if(watches.containsKey(completeMethodName)){
            stopWatch = watches.get(completeMethodName);
            stopWatch.stop();
        }
        return super.after(inv, instruction);
    }

}



3、添加注解
@Porfiled 标记在需要的controller方法上

4、log4j配置
<appender name="CoalescingStatistics"
		class="org.perf4j.log4j.AsyncCoalescingStatisticsAppender">
		<!-- The TimeSlice option is used to determine the time window for which 
			all received StopWatch logs are aggregated to create a single GroupedTimingStatistics 
			log. Here we set it to 10 seconds, overriding the default of 30000 ms -->
		<param name="TimeSlice" value="30000" />
		<appender-ref ref="fileAppender" />
	</appender>

	<!-- This file appender is used to output aggregated performance statistics -->
	<appender name="fileAppender" class="org.apache.log4j.FileAppender">
		<param name="File" value="/opt/jetty_dev/logs/perfStats.log" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%m%n" />
		</layout>
	</appender>

	<!-- Loggers -->
	<!-- The Perf4J logger. Note that org.perf4j.TimingLogger is the value of 
		the org.perf4j.StopWatch.DEFAULT_LOGGER_NAME constant. Also, note that additivity 
		is set to false, which is usually what is desired - this means that timing 
		statements will only be sent to this logger and NOT to upstream loggers. -->
	<logger name="org.perf4j.TimingLogger" additivity="false">
		<level value="INFO" />
		<appender-ref ref="CoalescingStatistics" />
	</logger>



默认是org.perf4j.TimingLogger

5、输出文件格式如下
Performance Statistics   2013-12-18 18:45:00 - 2013-12-18 18:45:30
Tag                                                  Avg(ms)         Min         Max     Std Dev       Count
class cn.focus.dc.app.pinge.controllers.FeedController.getFeedPicActoinList     18598.0       18598       18598         0.0           1

Performance Statistics   2013-12-18 18:45:30 - 2013-12-18 18:46:00
Tag                                                  Avg(ms)         Min         Max     Std Dev       Count

Performance Statistics   2013-12-18 18:46:00 - 2013-12-18 18:46:30
Tag                                                  Avg(ms)         Min         Max     Std Dev       Count

Performance Statistics   2013-12-18 18:46:30 - 2013-12-18 18:47:00
Tag                                                  Avg(ms)         Min         Max     Std Dev       Count
class cn.focus.dc.app.pinge.controllers.FeedController.getFeedPicActoinList       351.0         351         351         0.0           1

Performance Statistics   2013-12-18 18:47:00 - 2013-12-18 18:47:30
Tag                                                  Avg(ms)         Min         Max     Std Dev       Count

Performance Statistics   2013-12-18 18:48:00 - 2013-12-18 18:48:30
Tag                                                  Avg(ms)         Min         Max     Std Dev       Count
class cn.focus.dc.app.pinge.controllers.FeedController.getFeedPicActoinList       122.8          30         388       153.2           4


6、更多用法请参见:
http://aoyouzi.iteye.com/blog/1844297
http://www.oschina.net/question/129540_81069

你可能感兴趣的:(应用)