Spring自定义拦截器配置

前言:

公司生产环境频频被报性能瓶颈问题,为了找出问题的所在,现有的很多种方式能够解决,但是为了能够观测到具体的方法,我们想通过拦截那种耗时的方法,然后插入数据库,后台支撑系统能够实时的观察...

为了上述描述的结果,我们采用spring拦截器的方式,通过stopwatch的观察者模式,通过方法进入和方法退出来计算方法调用整个耗时情况

package spring.lifecycle;

import net.bull.javamelody.MonitoringSpringInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.util.StopWatch;

/**
 * Created by Young on 2015/9/26.
 */
class MonitoringSpringInterceptor2 extends MonitoringSpringInterceptor {

    public Object invoke(MethodInvocation invocation) throws Throwable {
        final String requestName = getRequestName(invocation);
        StopWatch stopWatch = new StopWatch(requestName);
        stopWatch.start(requestName);
        try {
            Object obj = super.invoke(invocation);
            return obj;
        } finally {
            stopWatch.stop();
            System.out.println(stopWatch.getTotalTimeSeconds());
        }
    }


}

 Spring的配置:

	<bean id="monitoringSpringInterceptor" class="spring.lifecycle.MonitoringSpringInterceptor2"></bean>

	<bean id="autoProxyCreator"
		  class="spring.lifecycle.BeanNameAutoProxyCreator">
		<property name="beanNames">
			<list>

				<value>*Service</value>
				<value>*DAO</value>
			</list>
		</property>
		<property name="interceptorFilter">
			<map>
				<entry key="*Service" value="transactionInterceptor,monitoringSpringInterceptor"/>
			</map>
		</property>

 结论:

想起来这些拦截,实现很简单,但是应用场景很频繁,对于生产环境监测,其实有更多需要的场景,如:bug跟踪、性能检测、方法参数、方法return等,所以功能场景很多,代码也不难。

猜你喜欢

转载自cywhoyi.iteye.com/blog/2246402