溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Spring MVC Interceptor 實(shí)現(xiàn)性能監(jiān)控的功能代碼

發(fā)布時間:2020-09-23 10:01:55 來源:腳本之家 閱讀:154 作者:程序員筆記 欄目:編程語言

利用Spring MVC 的 Interceptor 實(shí)現(xiàn)個簡易的性能監(jiān)控,計算一下每個url的執(zhí)行時間。

在 preHandle 方法中記錄當(dāng)前的時間戳到線程局部變量里,然后在afterCompletion方法中,用當(dāng)前的時間戳剪掉線程局部變量里的時間戳得出個運(yùn)行時間,并記錄到log里。

這只是個簡易的性能監(jiān)控,如果想長期正式的監(jiān)控性能,請選擇其它成熟的產(chǎn)品。

Interceptor

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
 
 
public class PerformanceInterceptor implements HandlerInterceptor {
 
  private final static Logger LOGGER = LoggerFactory.getLogger(PerformanceInterceptor.class);
 
  private NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>("performance");
 
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    startTimeThreadLocal.set(System.currentTimeMillis());
    return true;
  }
 
  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
      ModelAndView modelAndView) throws Exception {
    return;
  }
 
  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
      throws Exception {
    long currentTime = System.currentTimeMillis();
    long executeTime = currentTime - startTimeThreadLocal.get();
    LOGGER.info("uri:{} 執(zhí)行了 {} 毫秒", request.getRequestURI(), executeTime);
  }
 
}

這里的是NamedThreadLocal沒啥神器的,源碼如下:

package org.springframework.core;
 
import org.springframework.util.Assert;
 
public class NamedThreadLocal<T> extends ThreadLocal<T> {
 
  private final String name;
 
  public NamedThreadLocal(String name) {
    Assert.hasText(name, "Name must not be empty");
    this.name = name;
  }
 
  @Override
  public String toString() {
    return this.name;
  }
 
}

定義完Interceptor,注冊即可。

import java.util.List;
 
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.filter.OrderedCharacterEncodingFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
 
import com.vnierlai.scm.webapp.interceptor.PerformanceInterceptor;
 
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
 
  @Bean
  @ConditionalOnMissingBean(CharacterEncodingFilter.class)
  public CharacterEncodingFilter characterEncodingFilter() {
    CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
    filter.setEncoding("UTF-8");
    return filter;
  }
 
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new PerformanceInterceptor()).addPathPatterns("/**");
    super.addInterceptors(registry);
  }
 
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    // registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
  }
 
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI