- 注册拦截器
@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {
/**
* 定义拦截器调用链
*
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 日志追踪
registry.addInterceptor(new TraceLogInterceptor()).addPathPatterns("/**");
// 性能
registry.addInterceptor(new PerformanceInterceptor()).addPathPatterns("/**");
// 业务线
registry.addInterceptor(new MerchantInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.DisableCircularReferenceDetect
);
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastJsonHttpMessageConverter);
}
}
- 定义拦截器
public class TraceLogInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
MDC.put(TraceConstant.TRACE_KEY, UUID.randomUUID().toString().replace("-", ""));
String orderNo = request.getParameter(TraceConstant.ORDER_NO);
if (StringUtils.isBlank(orderNo)) {
orderNo = request.getParameter(TraceConstant.TRANS_ID);
}
MDC.put(TraceConstant.ORDER_NO, orderNo);
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
MDC.remove(TraceConstant.TRACE_KEY);
MDC.remove(TraceConstant.ORDER_NO);
}
}
另外对比SpringMVC 的拦截器,在SpringMVC.xml配置
<mvc:interceptors>
<!-- 日志追踪拦截器 -->
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/static/**"/>
<bean class="com.sq.dispatcher.spring.TraceLogInterceptor"/>
</mvc:interceptor>