SpringCloud微服务之OpenFeign添加traceId全链路监控

注册中心请参考:
https://blog.csdn.net/MadLifeBin/article/details/120332483
可搭建单机版用于 Demo 测试
服务提供与消费请参考:
https://blog.csdn.net/MadLifeBin/article/details/120420139
全链路监控添加日志支持maven添加依赖版本参考父POM
<dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId></dependency><dependency><groupId>org.slf4j</groupId><artifactId>log4j-over-slf4j</artifactId></dependency><dependency><groupId>org.slf4j</groupId><artifactId>jcl-over-slf4j</artifactId></dependency>服务双方添加日志配置文件

SpringCloud微服务之OpenFeign添加traceId全链路监控

文章插图
 
服务双方增加过滤器为每个请求创建traceId启动类增加注解@ServletComponentScan
@Order(1)@WebFilter(urlPatterns = "/*",filterName = "traceIdFilter")public class TraceIdFilter implements Filter {public final static String MDC_TRACE_ID = "traceId";@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest httpRequest = (HttpServletRequest) request;String traceId = httpRequest.getHeader(MDC_TRACE_ID);if (StringUtils.isBlank(traceId)) {traceId = IdUtil.fastSimpleUUID();;}MDC.put(MDC_TRACE_ID, traceId);ThreadLocalUtils.setTraceId(traceId);HttpServletResponse httpResponse = (HttpServletResponse) response;httpResponse.setHeader(MDC_TRACE_ID, traceId);chain.doFilter(request, response);}}同时将traceId写回到response的header中,方便在前端获取traceId.
consumer配置OpenFeign透传traceId@Componentpublic class OpenFeignRequestInterceptor implements RequestInterceptor {@Overridepublic void Apply(RequestTemplate requestTemplate) {String traceId = MDC.get(TraceIdFilter.MDC_TRACE_ID);requestTemplate.header(TraceIdFilter.MDC_TRACE_ID, traceId);}}测试服务双方的调用链路上增加打印日志语句LOGGER.info("userId:{}",userId);consumer
SpringCloud微服务之OpenFeign添加traceId全链路监控

文章插图
 
provider
SpringCloud微服务之OpenFeign添加traceId全链路监控

文章插图
 
根据traceId追踪日志
  1. 启动Eureka、Provider、Consumer
  2. 浏览器调用接口,在浏览器控制台拿到traceId
  3. 分别去对应服务的日志查找具体日志行 。

SpringCloud微服务之OpenFeign添加traceId全链路监控

文章插图
 

SpringCloud微服务之OpenFeign添加traceId全链路监控

文章插图
 
若搭配上阿里云的 SLS 或者 自行搭建的 EFLK,全链路日志只会更加方便

【SpringCloud微服务之OpenFeign添加traceId全链路监控】


    推荐阅读