分布式链路追踪—traceId生成与使用(MDC)

分布式链路追踪—traceId生成与使用(MDC),第1张

分布式链路追踪—traceId生成与使用(MDC)

        之前遇到过在分布式环境中不方便查找日志的问题,虽然现在的很多云服务环境都提供这种功能,但是在自己搭建的分布式环境中可以考虑应急的这样做,先记录下,以便下次快速使用

        注意:MDC-traceId在分布式环境中使用步骤(下面的3456四个类在分布式用到的工程中都需要添加,可以考虑添加到第三方工程中统一在pom中引入)  

        1、 引入log4j的同时需要注意去除冲突包

    org.springframework.boot
    spring-boot-starter
    
        
        
            org.springframework.boot
            spring-boot-starter-logging
        
    


    log4j
    log4j
    1.2.17


    org.slf4j
    slf4j-log4j12
    1.7.21
        2、resources 文件夹下添加[log4j.xml]配置文件
    
    
    
    
    
        
    



    
    

        3、添加[MDCUtils]自定义工具类

public class MDCUtils {

    
    public static String mdc(){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);

        String traceId;
        String traceIdKey = "traceId";
        if (request.getHeader(traceIdKey) == null) {
            traceId = UUID.randomUUID().toString();
        } else {
            traceId = request.getHeader(traceIdKey);
        }
        return traceId;
    }

}

        4、添加拦截器[LogInterceptor]为每一个请求头添加[traceId]

public class LogInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String traceIdKey = "traceId";
        String traceId = MDCUtils.mdc();
        request.setAttribute(traceIdKey, traceId);
        MDC.clear();
        MDC.put(traceIdKey, traceId);
        return true;
    }
}

        5、注册拦截器

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LogInterceptor()).addPathPatterns("/test
            URIBuilder uriBuilder = new URIBuilder(url);
            // 第一种添加参数的形式
            
            // 第二种添加参数的形式
            // 加载参数
            if (!CollectionUtils.isEmpty(paramMap)) {
                List paramertersList = new linkedList<>();

                Set keys = paramMap.keySet();
                for (String s : keys) {
                    String key = String.valueOf(s);
                    String value = ObjectUtils.isEmpty(paramMap.get(key)) ? null : paramMap.get(key).toString();
                    if (ObjectUtils.isNotEmpty((value))) {
                        BasicNamevaluePair param1 = new BasicNamevaluePair(key, value);
                        paramertersList.add(param1);
                    }
                }
                uriBuilder.setParameters(paramertersList);
            }

            // 根据带参数的URI对象构建GET请求对象
            HttpGet httpGet = new HttpGet(uriBuilder.build());

            if (headMap != null) {
                for (Map.Entry entry : headMap.entrySet()) {
                    if (entry.getValue() != null) {
                        httpGet.addHeader(entry.getKey(), entry.getValue().toString());
                    }
                }
            }

            String traceId = MDC.get("traceId");
            httpGet.addHeader("traceId", traceId);
            httpGet.addHeader("Accept", "*
            // 创建请求参数
            if (!CollectionUtils.isEmpty(paramMap)) {
                List paramertersList = new linkedList<>();

                Set keys = paramMap.keySet();
                for (String s : keys) {
                    String key = String.valueOf(s);
                    String value = ObjectUtils.isEmpty(paramMap.get(key)) ? null : paramMap.get(key).toString();
                    if (ObjectUtils.isNotEmpty(value)) {
                        BasicNamevaluePair param1 = new BasicNamevaluePair(key, value);
                        paramertersList.add(param1);
                    }
                }
                // 使用URL实体转换工具
                entityParam = new UrlEncodedFormEntity(paramertersList, "UTF-8");
            }

            httpPost.setEntity(entityParam);

            if (headMap != null) {
                for (Map.Entry entry : headMap.entrySet()) {
                    if (entry.getValue() != null) {
                        httpPost.addHeader(entry.getKey(), entry.getValue().toString());
                    }
                }
            }

            String traceId = MDC.get("traceId");
            httpPost.addHeader("traceId", traceId);
            httpPost.addHeader("Accept", "*/*");
            httpPost.addHeader("Connection", "Keep-Alive");
            httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
            // 传输的类型
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");

            // 执行请求
            response = httpClient.execute(httpPost);
            // 获得响应的实体对象
            HttpEntity entity = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            entityStr = EntityUtils.toString(entity, "UTF-8");

            // 此处获取所有的响应头信息并进行打印
            System.out.println(Arrays.toString(response.getAllHeaders()));
        } catch (ClientProtocolException e) {
            System.err.println("Http协议出现问题");
            e.printStackTrace();
        } catch (ParseException e) {
            System.err.println("解析错误");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("IO异常");
            e.printStackTrace();
        } finally {
            // 释放连接
            if (null != response) {
                try {
                    response.close();
                    httpClient.close();
                } catch (IOException e) {
                    System.err.println("释放连接出错");
                    e.printStackTrace();
                }
            }
        }
        return entityStr;
    }

}

        7、请求实例: 1-调用-2

1:
2021-07-21 11:14:30.168 - [283ba7ba-8910-48e3-8864-cd8de7af07cb] INFO  com.example.demolog4jmdc.controller.TestController:27  - 测试 test1
2021-07-21 11:14:30.169 - [283ba7ba-8910-48e3-8864-cd8de7af07cb] INFO  com.example.demolog4jmdc.controller.TestService:18  - =====TestService.test1
2021-07-21 11:14:30.169 - [283ba7ba-8910-48e3-8864-cd8de7af07cb] INFO  com.example.demolog4jmdc.controller.TestService:22  - =====TestService.test3
2021-07-21 11:14:30.169 - [283ba7ba-8910-48e3-8864-cd8de7af07cb] INFO  com.example.demolog4jmdc.controller.TestService:26  - =====TestService.test3
2021-07-21 11:14:30.771 - [283ba7ba-8910-48e3-8864-cd8de7af07cb] INFO  com.example.demolog4jmdc.controller.TestController:35  - ===s===aaaaa

2:
2021-07-21 11:14:30.746 - [283ba7ba-8910-48e3-8864-cd8de7af07cb] INFO  com.example.demolog4jmdc2.controller.TestController:26  - 测试 test1-traceId:283ba7ba-8910-48e3-8864-cd8de7af07cb

        到此分布式链路追踪—traceId生成与使用(MDC)介绍完成。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5702054.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存