<返回更多

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

2022-04-26    MadLifeBin
加入收藏

注册中心

请参考:
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";

    @Override
    public 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

@Component
public class OpenFeignRequestInterceptor implements RequestInterceptor {

    @Override
    public 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,全链路日志只会更加方便

声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>