您好,登錄后才能下訂單哦!
這篇“全局請求怎么添加TraceId”文章的知識點大部分人都不太理解,所以小編給大家總結了以下內容,內容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“全局請求怎么添加TraceId”文章吧。
@Component public class TraceIdInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String traceId = String.format("%s - %s",request.getRequestURI(), UUID.fastUUID().toString(true)); MDC.put("traceId", traceId); return true; }
注冊攔截器
@Component @RequiredArgsConstructor public class GlobalWebMvcConfigurer implements WebMvcConfigurer { private final TraceIdInterceptor traceIdInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(traceIdInterceptor); } }
@Data @NoArgsConstructor @AllArgsConstructor public class CommonResponse<T> implements Serializable { /** 錯誤碼 */ private Integer code; /** 錯誤消息 */ private String message; /** 泛型響應數據 */ private T Data; private String traceId; public CommonResponse(Integer code, String message) { this.code = code; this.message = message; this.traceId = MDC.get("traceId"); } }
logback.xml
<?xml version="1.0" encoding="UTF-8"?> <configuration> <property name="LOG_PATTERN" value="%d{yyyy-MM-dd} %d{HH:mm:ss.SSS} [%highlight(%-5level)] [%boldYellow(%X{traceId})] [%boldYellow(%thread)] %boldGreen(%logger{36} %F.%L) %msg%n"> </property> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>${LOG_PATTERN}</pattern> </encoder> <!-- 控制臺打印INFO及以上級別的日志 --> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> <level>INFO</level> </filter> </appender> <root> <appender-ref ref="STDOUT"/> </root> </configuration>
接口返回值
{ "code": 0, "message": "", "traceId": "/commerce-user/user/findById - 73e470120ef24d57a111de6b671d030b", "data": { "id": 1, "username": "test1", "password": "test", "extraInfo": "{}", "createTime": "2022-06-20T09:23:18.000+00:00", "updateTime": "2022-06-20T09:23:18.000+00:00", "balance": 0 } }
日志
如此,如果線上有接口出現問題,拿著 traceId 到日志文件搜索,就能檢索到該請求的日志調用鏈路,處理問題就變得簡單了。
因為是 ThreadLocal ,異步任務必然是獲取不到 traceId 的,需要再線程池配置中手動添加。
線程池配置
@Configuration public class AsyncConfig implements AsyncConfigurer { @Bean @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); executor.setMaxPoolSize(20); executor.setQueueCapacity(20); executor.setKeepAliveSeconds(60); executor.setThreadNamePrefix("user-async-"); // 等待所有任務結果候再關閉線程池 executor.setWaitForTasksToCompleteOnShutdown(true); executor.setAwaitTerminationSeconds(60); // 定義拒絕策略 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //設置線程裝飾器 executor.setTaskDecorator(runnable -> ThreadMdcUtils.wrapAsync(runnable, MDC.getCopyOfContextMap())); // 初始化線程池, 初始化 core 線程 executor.initialize(); return executor; } }
public class ThreadMdcUtils { public static Runnable wrapAsync(Runnable task, Map<String,String> context){ return () -> { if(context==null){ MDC.clear(); }else { MDC.setContextMap(context); } if(MDC.get("traceId")==null){ MDC.put("traceId", UUID.fastUUID().toString(true)); } try { task.run(); }finally { MDC.clear(); } }; } }
再次測試
以上就是關于“全局請求怎么添加TraceId”這篇文章的內容,相信大家都有了一定的了解,希望小編分享的內容對大家有幫助,若想了解更多相關的知識內容,請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。