Spring/Spring boot项目接入traceId

简介

分布式系统中,由多个服务构成,每个请求路由过来后,会在多个服务中留下追踪ID,可以基于此追踪ID排查问题,分析请求的执行链路。

业界也有比较成熟的链路追踪ID方案,比如Skywalking,它基于动态字节码技术,本身会增加系统的复杂性,以及它需要单独部署服务对信息进行采集,这对于ToB资源敏感的场景下并不适用。traceID是基于自身必需框架开发的,主要技术是日志MDC、跨线程包装、中间件拦截器,所以可以几乎不增加任何额外资源开销。

本次traceId支持dubbo,kafka,http请求,线程池

接入步骤

1、日志中增加traceId变量

logback.xml日志配置,当然你也可以自定义格式,变量%X{traceId}是追踪ID替换值:

若框架使用log4j,在日志格式中增加%X{traceId}变量

<property name="FILE_LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - [%X{traceId}] - %msg%n"/>

2、代码实现

2.0 依赖,不同实现按需添加依赖,例如kafka相关接入traceId,项目本身已经引入kafka

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2.1 http请求

编写拦截器

public class TraceWebInterceptor extends HandlerInterceptorAdapter {private static final Logger LOGGER = LoggerFactory.getLogger(TraceWebInterceptor.class);@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {request.setAttribute("startTime", System.currentTimeMillis());//traceOrigin、traceCaller、traceIdString traceOrigin = request.getHeader(TraceConstants.LOG_TRACE_ORIGIN);String traceCaller = request.getHeader(TraceConstants.LOG_TRACE_CALLER);String traceId = request.getHeader(TraceConstants.LOG_TRACE_ID);//如果不存在traceId需要生成if (StringUtils.isBlank(traceId)) {boolean generate = TraceUtil.loadTraceInfo();if(generate) {LOGGER.debug("[生成追踪信息]" + TraceUtil.getTraceInfoString());}}else {//设置MDCMDC.put(TraceConstants.LOG_TRACE_ORIGIN, traceOrigin);MDC.put(TraceConstants.LOG_TRACE_CALLER, traceCaller);MDC.put(TraceConstants.LOG_TRACE_ID, traceId);}//IPString traceIp = IpUtil.getIp(request);MDC.put(TraceConstants.LOG_TRACE_IP, traceIp);//响应返回response.setHeader(TraceConstants.LOG_TRACE_ID, TraceUtil.getTraceId());return super.preHandle(request, response, handler);}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws IOException {if (LOGGER.isInfoEnabled()) {long upmsStartTime = (long) request.getAttribute("startTime");long upmsEndTime = System.currentTimeMillis();long upmsIntervalTime = upmsEndTime - upmsStartTime;LOGGER.info("{} {}接口耗时{}毫秒", request.getRequestURL(), request.getMethod(), upmsIntervalTime);}MDC.clear();}

编写Config类, 将拦截器TraceWebInterceptor添加到容器

@Configuration
@ConditionalOnClass({HandlerInterceptorAdapter.class, MDC.class, HttpServletRequest.class})
public class TraceWebAutoConfiguration implements WebMvcConfigurer {private static List<String> EXCLUDE_PATHS = new ArrayList<>();@Value("${" + TraceConstants.CONFIG_TRACE_EXCLUDE_PATHS + ":}")private String excludePaths;@Beanpublic TraceWebInterceptor traceWebInterceptor() {return new TraceWebInterceptor();}@Overridepublic void addInterceptors(InterceptorRegistry registry) {EXCLUDE_PATHS.add("/error");EXCLUDE_PATHS.add("/actuator/**");if (StringUtils.isNotBlank(excludePaths)) {if (excludePaths.contains(",")) {String[] split = excludePaths.split(",");EXCLUDE_PATHS.addAll(Arrays.asList(split));} else {EXCLUDE_PATHS.add(excludePaths);}}//该方式不能过全部过滤掉registry.addInterceptor(traceWebInterceptor()).order(-100).excludePathPatterns(EXCLUDE_PATHS);}
}

工具类

public class IpUtil {private static final String UNKNOWN = "unknown";public static String getIp(HttpServletRequest request) {if (request == null) {return UNKNOWN;}String ip = request.getHeader("x-forwarded-for");if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {ip = request.getHeader("Proxy-Client-IP");}if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {ip = request.getHeader("X-Forwarded-For");}if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {ip = request.getHeader("WL-Proxy-Client-IP");}if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {ip = request.getHeader("X-Real-IP");}if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {ip = request.getRemoteAddr();}return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;}
}public class TraceConstants {public static final String LOG_TRACE_ORIGIN = "traceOrigin";public static final String LOG_TRACE_CALLER = "traceCaller";public static final String LOG_TRACE_IP = "traceIp";public static final String LOG_TRACE_ID = "traceId";public static final String CONFIG_TRACE_EXCLUDE_PATHS = "trace.exclude.paths";public TraceConstants() {}
}import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;public class TraceUtil {private static boolean simbaHttpClientInterceptorFlag = true;private static boolean sdkInterceptorFlag = false;private static String applicationName;public TraceUtil() {}public static void setApplicationName(String applicationName) {TraceUtil.applicationName = applicationName;}public static String getApplicationName() {return applicationName;}public static boolean getSimbaHttpClientInterceptorFlag() {return simbaHttpClientInterceptorFlag;}public static void setSimbaHttpClientInterceptorFlag(boolean simbaHttpClientInterceptorFlag) {TraceUtil.simbaHttpClientInterceptorFlag = simbaHttpClientInterceptorFlag;}public static boolean getSdkInterceptorFlag() {return sdkInterceptorFlag;}public static void setSdkInterceptorFlag(boolean sdkInterceptorFlag) {TraceUtil.sdkInterceptorFlag = sdkInterceptorFlag;}public static void setTraceCaller(String traceCaller) {MDC.put("traceCaller", traceCaller);}public static String getTraceCaller() {return MDC.get("traceCaller");}public static void setTraceOrigin(String traceOrigin) {MDC.put("traceOrigin", traceOrigin);}public static String getTraceOrigin() {return MDC.get("traceOrigin");}public static void setTraceId(String traceId) {MDC.put("traceId", traceId);}public static void removeTraceId() {MDC.remove("traceId");}public static void clearMdc() {MDC.clear();}public static String getTraceId() {return MDC.get("traceId");}public static String genTraceId() {return UUID.randomUUID().toString().replace("-", "");}public static String getTraceIp() {return MDC.get("traceIp");}public static void setTraceIp(String traceIp) {MDC.put("traceIp", traceIp);}public static boolean loadTraceInfo() {boolean generate = false;String traceId = getTraceId();if (StringUtils.isBlank(traceId)) {traceId = genTraceId();generate = true;}setTraceId(traceId);return generate;}public static String getTraceInfoString() {return "TraceId:" + getTraceId() + ". traceCaller:" + getTraceCaller() + ". traceOrigin:" + getTraceOrigin();}
}import org.slf4j.MDC;import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;public class WrapUtil {public static <T> Callable<T> wrap(final Callable<T> callable, final Map<String, String> context) {return () -> {if (context == null) {MDC.clear();} else {MDC.setContextMap(context);}TraceUtil.loadTraceInfo();try {return callable.call();} finally {MDC.clear();}};}public static <T> Callable<T> wrap(final Callable<T> callable) {return wrap(callable, MDC.getCopyOfContextMap());}public static Runnable wrap(final Runnable runnable, final Map<String, String> context) {return () -> {if (context == null) {MDC.clear();} else {MDC.setContextMap(context);}TraceUtil.loadTraceInfo();try {runnable.run();} finally {MDC.clear();}};}public static Runnable wrap(final Runnable runnable) {return wrap(runnable, MDC.getCopyOfContextMap());}public static ThreadPoolExecutor newThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,RejectedExecutionHandler handler) {return new ThreadPoolExecutorMdcWrapper(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);}public static ThreadPoolExecutor newThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {return new ThreadPoolExecutorMdcWrapper(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);}public static ThreadPoolExecutor newThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,BlockingQueue<Runnable> workQueue) {return new ThreadPoolExecutorMdcWrapper(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);}public static ThreadPoolExecutor newThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,BlockingQueue<Runnable> workQueue,RejectedExecutionHandler handler) {return new ThreadPoolExecutorMdcWrapper(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);}public static ForkJoinPool newForkJoinPool() {return new ForkJoinPoolMdcWrapper();}public static class ThreadPoolExecutorMdcWrapper extends ThreadPoolExecutor {public ThreadPoolExecutorMdcWrapper(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,BlockingQueue<Runnable> workQueue) {super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);}public ThreadPoolExecutorMdcWrapper(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);}public ThreadPoolExecutorMdcWrapper(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);}public ThreadPoolExecutorMdcWrapper(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,RejectedExecutionHandler handler) {super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);}@Overridepublic void execute(Runnable task) {super.execute(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));}@Overridepublic <T> Future<T> submit(Runnable task, T result) {return super.submit(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), result);}@Overridepublic <T> Future<T> submit(Callable<T> task) {return super.submit(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));}@Overridepublic Future<?> submit(Runnable task) {return super.submit(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));}}public static class ForkJoinPoolMdcWrapper extends ForkJoinPool {public ForkJoinPoolMdcWrapper() {super();}public ForkJoinPoolMdcWrapper(int parallelism) {super(parallelism);}public ForkJoinPoolMdcWrapper(int parallelism, ForkJoinWorkerThreadFactory factory,Thread.UncaughtExceptionHandler handler, boolean asyncMode) {super(parallelism, factory, handler, asyncMode);}@Overridepublic void execute(Runnable task) {super.execute(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));}@Overridepublic <T> ForkJoinTask<T> submit(Runnable task, T result) {return super.submit(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), result);}@Overridepublic <T> ForkJoinTask<T> submit(Callable<T> task) {return super.submit(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));}}
}

2.2 Spring中的@Async注解中的线程池

@Configuration
public class TaskExecutorConfig {@Beanpublic TaskExecutor taskExecutor() {ThreadPoolTaskExecutor executor = TraceSpringTraceWrapUtil.newThreadPoolTaskExecutor();// 设置核心线程数executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());// 设置最大线程数executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 10);// 设置队列容量executor.setQueueCapacity(Runtime.getRuntime().availableProcessors() * 10);// 设置线程活跃时间(秒)executor.setKeepAliveSeconds(10);// 设置默认线程名称executor.setThreadNamePrefix("scheduled-");// 设置拒绝策略executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());// 等待所有任务结束后再关闭线程池executor.setWaitForTasksToCompleteOnShutdown(true);executor.initialize();return executor;}}

相关工具类 

import com.startdt.license.util.WrapUtil;
import org.slf4j.MDC;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.util.concurrent.ListenableFuture;import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;public class TraceSpringTraceWrapUtil extends WrapUtil {public static class ThreadPoolTaskExecutorMdcWrapper extends ThreadPoolTaskExecutor {@Overridepublic void execute(Runnable task) {super.execute(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));}@Overridepublic void execute(Runnable task, long startTimeout) {super.execute(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), startTimeout);}@Overridepublic <T> Future<T> submit(Callable<T> task) {return super.submit(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));}@Overridepublic Future<?> submit(Runnable task) {return super.submit(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));}@Overridepublic ListenableFuture<?> submitListenable(Runnable task) {return super.submitListenable(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));}@Overridepublic <T> ListenableFuture<T> submitListenable(Callable<T> task) {return super.submitListenable(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));}}public static class ScheduledThreadPoolTaskExecutorMdcWrapper extends ScheduledThreadPoolExecutor {public ScheduledThreadPoolTaskExecutorMdcWrapper(int corePoolSize) {super(corePoolSize);}public ScheduledThreadPoolTaskExecutorMdcWrapper(int corePoolSize, ThreadFactory threadFactory) {super(corePoolSize, threadFactory);}@Overrideprotected <V> RunnableScheduledFuture<V> decorateTask(Callable<V> callable, RunnableScheduledFuture<V> task) {return super.decorateTask(WrapUtil.wrap(callable, MDC.getCopyOfContextMap()), task);}@Overrideprotected <V> RunnableScheduledFuture<V> decorateTask(Runnable runnable, RunnableScheduledFuture<V> task) {return super.decorateTask(WrapUtil.wrap(runnable, MDC.getCopyOfContextMap()), task);}@Overridepublic ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {return super.schedule(WrapUtil.wrap(command, MDC.getCopyOfContextMap()), delay, unit);}@Overridepublic ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {return super.scheduleAtFixedRate(WrapUtil.wrap(command, MDC.getCopyOfContextMap()), initialDelay, period, unit);}}public static class ThreadPoolTaskSchedulerWrapper extends ThreadPoolTaskScheduler {@Overridepublic ScheduledFuture<?> schedule(Runnable task, Date startTime) {return super.schedule(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), startTime);}@Overridepublic ScheduledFuture<?> schedule(Runnable task, Trigger trigger) {return super.schedule(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), trigger);}@Overridepublic ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) {return super.scheduleAtFixedRate(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), period);}@Overridepublic ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period) {return super.scheduleAtFixedRate(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), startTime, period);}@Overridepublic ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay) {return super.scheduleWithFixedDelay(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), delay);}}public static ThreadPoolTaskExecutor newThreadPoolTaskExecutor() {return new ThreadPoolTaskExecutorMdcWrapper();}public static ScheduledThreadPoolExecutor newScheduledThreadPoolExecutor(int corePoolSize) {return new ScheduledThreadPoolTaskExecutorMdcWrapper(corePoolSize);}public static ScheduledThreadPoolExecutor newScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory) {return new ScheduledThreadPoolTaskExecutorMdcWrapper(corePoolSize, threadFactory);}public static ThreadPoolTaskScheduler newThreadPoolTaskScheduler() {return new ThreadPoolTaskSchedulerWrapper();}}

2.3 spring线程池

import com.startdt.license.util.WrapUtil;
import org.slf4j.MDC;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.util.concurrent.ListenableFuture;import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;public class TraceSpringTraceWrapUtil extends WrapUtil {public static class ThreadPoolTaskExecutorMdcWrapper extends ThreadPoolTaskExecutor {@Overridepublic void execute(Runnable task) {super.execute(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));}@Overridepublic void execute(Runnable task, long startTimeout) {super.execute(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), startTimeout);}@Overridepublic <T> Future<T> submit(Callable<T> task) {return super.submit(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));}@Overridepublic Future<?> submit(Runnable task) {return super.submit(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));}@Overridepublic ListenableFuture<?> submitListenable(Runnable task) {return super.submitListenable(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));}@Overridepublic <T> ListenableFuture<T> submitListenable(Callable<T> task) {return super.submitListenable(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));}}public static class ScheduledThreadPoolTaskExecutorMdcWrapper extends ScheduledThreadPoolExecutor {public ScheduledThreadPoolTaskExecutorMdcWrapper(int corePoolSize) {super(corePoolSize);}public ScheduledThreadPoolTaskExecutorMdcWrapper(int corePoolSize, ThreadFactory threadFactory) {super(corePoolSize, threadFactory);}@Overrideprotected <V> RunnableScheduledFuture<V> decorateTask(Callable<V> callable, RunnableScheduledFuture<V> task) {return super.decorateTask(WrapUtil.wrap(callable, MDC.getCopyOfContextMap()), task);}@Overrideprotected <V> RunnableScheduledFuture<V> decorateTask(Runnable runnable, RunnableScheduledFuture<V> task) {return super.decorateTask(WrapUtil.wrap(runnable, MDC.getCopyOfContextMap()), task);}@Overridepublic ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {return super.schedule(WrapUtil.wrap(command, MDC.getCopyOfContextMap()), delay, unit);}@Overridepublic ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {return super.scheduleAtFixedRate(WrapUtil.wrap(command, MDC.getCopyOfContextMap()), initialDelay, period, unit);}}public static class ThreadPoolTaskSchedulerWrapper extends ThreadPoolTaskScheduler {@Overridepublic ScheduledFuture<?> schedule(Runnable task, Date startTime) {return super.schedule(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), startTime);}@Overridepublic ScheduledFuture<?> schedule(Runnable task, Trigger trigger) {return super.schedule(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), trigger);}@Overridepublic ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) {return super.scheduleAtFixedRate(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), period);}@Overridepublic ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period) {return super.scheduleAtFixedRate(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), startTime, period);}@Overridepublic ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay) {return super.scheduleWithFixedDelay(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), delay);}}public static ThreadPoolTaskExecutor newThreadPoolTaskExecutor() {return new ThreadPoolTaskExecutorMdcWrapper();}public static ScheduledThreadPoolExecutor newScheduledThreadPoolExecutor(int corePoolSize) {return new ScheduledThreadPoolTaskExecutorMdcWrapper(corePoolSize);}public static ScheduledThreadPoolExecutor newScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory) {return new ScheduledThreadPoolTaskExecutorMdcWrapper(corePoolSize, threadFactory);}public static ThreadPoolTaskScheduler newThreadPoolTaskScheduler() {return new ThreadPoolTaskSchedulerWrapper();}}

2.4 dubbo rpc

@Activate(group = {DubboConstants.CONSUMER} , order = -9999)
public class TraceDubboConsumerFilter implements Filter {private Logger logger = LoggerFactory.getLogger(TraceDubboConsumerFilter.class);@Overridepublic Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {String traceId = TraceUtil.getTraceId();String traceCaller = TraceUtil.getTraceCaller();String traceOrigin = TraceUtil.getTraceOrigin();if(StringUtils.isBlank(traceId)) {traceId = TraceUtil.genTraceId();traceCaller = TraceUtil.getApplicationName();traceOrigin = TraceUtil.getApplicationName();logger.debug("[仅生成追踪信息]traceId:{}. traceCaller:{}. traceOrigin:{}", traceId, traceCaller, traceOrigin);}RpcContext.getContext().setAttachment(TraceConstants.LOG_TRACE_ID, traceId);RpcContext.getContext().setAttachment(TraceConstants.LOG_TRACE_CALLER, traceCaller);RpcContext.getContext().setAttachment(TraceConstants.LOG_TRACE_ORIGIN, traceOrigin);return invoker.invoke(invocation);}
}
@Activate(group = {DubboConstants.PROVIDER}, order = -10000)
public class TraceDubboProviderFilter implements Filter {private Logger logger = LoggerFactory.getLogger(TraceDubboConsumerFilter.class);@Overridepublic Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {//traceOrigin、traceCaller、traceIdString traceId = invocation.getAttachment(TraceConstants.LOG_TRACE_ID);String traceCaller = invocation.getAttachment(TraceConstants.LOG_TRACE_CALLER);String traceOrigin = invocation.getAttachment(TraceConstants.LOG_TRACE_ORIGIN);//如果不存在traceId需要生成if (StringUtils.isBlank(traceId)) {boolean generate = TraceUtil.loadTraceInfo();if(generate) {logger.info("[生成追踪信息]" + TraceUtil.getTraceInfoString());}}else {//设置MDCMDC.put(TraceConstants.LOG_TRACE_ORIGIN, traceOrigin);MDC.put(TraceConstants.LOG_TRACE_CALLER, traceCaller);MDC.put(TraceConstants.LOG_TRACE_ID, traceId);}//IPString clientIp = RpcContext.getContext().getRemoteHost();MDC.put(TraceConstants.LOG_TRACE_IP, clientIp);try {return invoker.invoke(invocation);} finally {MDC.clear();}}
}

2.5 kafka

生产者:

a:增加配置项:

spring:kafka:producer:properties:interceptor:classes: com.trace.kafka.TraceProducerInterceptor

b.kafkaTemplateAutoConfig代码中增加

if (StringUtils.isNotBlank(producerInterceptors)) {props.put(ProducerConfig.INTERCEPTOR_CLASSES_CONFIG, producerInterceptors);
}

消费者前增加代码:

TraceConsumerUtil.trace(consumerRecord);

 消费者工具类

import com.startdt.simba.boot.common.constants.TraceConstants;
import com.startdt.simba.boot.common.utils.TraceUtil;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.common.header.Header;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;public class TraceConsumerUtil {private static final Logger LOGGER = LoggerFactory.getLogger(TraceConsumerUtil.class);public static void trace(ConsumerRecord consumerRecord) {try {if(consumerRecord == null) {return;}Iterable<Header> headers = consumerRecord.headers().headers(TraceConstants.LOG_TRACE_ID);Header firstHeader = null;for(Header header : headers) {if(firstHeader != null) {break;}if(header != null) {firstHeader = header;}}if(firstHeader == null) {TraceUtil.setTraceId(TraceUtil.genTraceId());}else {TraceUtil.setTraceId(new String(firstHeader.value()));}}catch (Exception ex) {LOGGER.warn("Kafka tracking ID setting failed, reason:" + ex.getMessage(), ex);}}
}

 生产者拦截器

public class TraceProducerInterceptor implements ProducerInterceptor {private static final Logger LOGGER = LoggerFactory.getLogger(TraceProducerInterceptor.class);@Overridepublic ProducerRecord onSend(ProducerRecord record) {try {TraceUtil.loadTraceInfo();String traceId = TraceUtil.getTraceId();if(StrUtil.isNotBlank(traceId)) {record.headers().add(TraceConstants.LOG_TRACE_ID, traceId.getBytes());}}catch (Exception ex) {LOGGER.warn("Kafka tracking ID setting failed, reason:" + ex.getMessage(), ex);}return record;}@Overridepublic void onAcknowledgement(RecordMetadata metadata, Exception exception) {}@Overridepublic void close() {}@Overridepublic void configure(Map<String, ?> configs) {}
}

2.6 线程池使用步骤

替换ThreadPoolExecutor为包装类

    private static ThreadPoolExecutor executor = new TraceWrapUtil.ThreadPoolExecutorMdcWrapper(defaultPoolSize, defaultPoolSize,10L,TimeUnit.SECONDS,new ArrayBlockingQueue<>(1000),new NameThreadFactory("warn.message.handler."), new AbortPolicy());

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/641587.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python 抓包tcp数据拷贝转发

在Python中&#xff0c;你可以使用scapy库进行抓包&#xff0c;使用shutil或io库进行数据的拷贝&#xff0c;以及使用socket库进行数据转发。下面是一个简单的示例&#xff0c;展示了如何进行这些操作&#xff1a; 首先&#xff0c;你需要安装必要的库。你可以使用pip来安装它…

Java算法 leetcode简单刷题记录4

Java算法 leetcode简单刷题记录4 买卖股票的最佳时机&#xff1a; https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/ 笨办法&#xff1a; 记录当天的值及之后的最大值&#xff0c;相减得到利润&#xff1b; 所有的天都计算下&#xff0c;比较得到利润最大值&…

PyTorch视觉工具箱:图像变换与上采样技术详解(1)

目录 Pytorch中Vision functions详解 pixel_shuffle 用途 用法 使用技巧 注意事项 参数 数学理论公式 示例代码及输出 pixel_unshuffle 用途 用法 使用技巧 注意事项 参数 数学理论公式 示例代码及输出 pad 用途 用法 使用技巧 注意事项 参数 示例代码…

智能机器人与旋量代数(9)

Chapt 3. 螺旋运动与旋量代数 3.1 螺旋运动 螺旋运动是关于一条空间直线的一个旋转运动&#xff0c;并伴随沿此直线的一个平移。是一种刚体绕空间轴 s s s旋转 θ \theta θ角&#xff0c;再沿该轴平移距离 d d d的复合运动&#xff0c;类似螺母沿螺纹做进给运动的情形。 一…

2024年【焊工(初级)】考试内容及焊工(初级)新版试题

题库来源&#xff1a;安全生产模拟考试一点通公众号小程序 焊工&#xff08;初级&#xff09;考试内容参考答案及焊工&#xff08;初级&#xff09;考试试题解析是安全生产模拟考试一点通题库老师及焊工&#xff08;初级&#xff09;操作证已考过的学员汇总&#xff0c;相对有…

docker 使用 vcs/2018 Verdi等 eda 软件

好不容易在ubuntu 安装好了eda软件&#xff0c;转眼就发现了自己的无知。 有博主几年前就搞定了docker上的EDA工具。而且更全&#xff0c;更简单。只恨自己太无知啊。 Synopsys EDA Tools docker image - EDA资源使用讨论 - EETOP 创芯网论坛 (原名&#xff1a;电子顶级开发网…

python解决从有序数组中寻找中位数

如果给定两个长度分别是m和n的有序数组array1和array2&#xff0c;需要对这两个有序数组找出其中的中位数&#xff0c;需要保证时间复杂度是O(long(min(m,n))&#xff0c;空间复杂度是O(1)。如下例子&#xff1a; 添加图片注释&#xff0c;不超过 140 字&#xff08;可选&#…

【教程】混淆Dart 代码

什么是代码混淆&#xff1f; 代码混淆是一种将应用程序二进制文件转换为功能上等价&#xff0c;但人类难于阅读和理解的行为。在编译 Dart 代码时&#xff0c;混淆会隐藏函数和类的名称&#xff0c;并用其他符号替代每个符号&#xff0c;从而使攻击者难以进行逆向工程。 Flut…

ChatGPT和文心一言哪个更好用?

目录 一、ChatGPT和文心一言大模型的对比分析 1.1 二者训练的数据情况分析 1.2 训练大模型数据规模和参数对比 1.3 二者3.5版本大模型对比总结 二、ChatGPT和文心一言功能对比分析 2.1 二者产品提供的功能情况分析 2.2 测试一下各种功能的特性 2.2.1 文本创作能力 2.2…

Redis通过dump.rdb恢复数据

Redis通过dump.rdb恢复数据 注意3个配置参数&#xff1a; appendonly no dbfilename dump.rdb dir /var/lib/redisappendonly 设置成no&#xff0c;redis启动时会把/var/lib/redis该文件夹可指定目录下的dump.rdb 中的数据恢复。dir 和dbfilename设置rdb文件名称 都可以设置。…

电脑提示“No Boot Device”怎么办?

在Windows 11/10/8/7启动时遇到错误如“No Boot Device Found”和“未找到引导设备硬盘3F0”时&#xff0c;会导致电脑无法正常开机。那么&#xff0c;No Boot Device错误该怎么修复呢&#xff1f;下面我们就来了解一下。 修复 1. 检查启动顺序并将BIOS的设置重置为默认值 为…

非线性最小二乘问题的数值方法 —— 狗腿法 Powell‘s Dog Leg Method (II, Python 简单实例)

Title: 非线性最小二乘问题的数值方法 —— 狗腿法 Powell‘s Dog Leg Method (II, Python 简单实例) 姊妹博文 非线性最小二乘问题的数值方法 —— 狗腿法 Powell‘s Dog Leg Method (I - 原理与算法) 0.前言 本篇博文作为对前述 “非线性最小二乘问题的数值方法 —— 狗腿法…

【mars3d】内置的右键测量菜单单击关闭按钮无法关闭测量结果说明

1.【mars3d】内置的右键测量菜单单击关闭按钮无法关闭测量结果说明 2.内置的右击地图查看此处坐标&#xff0c;出现的弹框按钮同样无法关闭的解决方案。 解决说明&#xff1a; 1.这个问题和mars3d没有关系&#xff0c;是and那边的问题&#xff0c;需要尝试固定下vue版本3.3.0或…

测试 yolov8 分割模型 边缘检测

发现 cfg/default.yaml 参数 mask_ratio 等于4 直接训练如下边缘分割标签,推理时mask 稀疏&#xff0c;训练时分数偏低,mask_ratio 改为1训练时打印的mask 的 P指标一直为0,将imgsz原图size 训练分数也不高 标注用的是labelme多边形 阅读源码发现可能是因为mask缩放导致 且出现…

springboot配置项动态刷新

文章目录 一&#xff0c;序言二&#xff0c;准备工作1. pom.xml引入组件2. 配置文件示例 三&#xff0c;自定义配置项动态刷新编码实现1. 定义自定义配置项对象2. 添加注解实现启动时自动注入3. 实现yml文件监听以及文件变化处理 四&#xff0c;yaml文件转换为java对象1. 无法使…

IPv4 开始收费!新的 IT 灾难?

对于想要继续使用公共IPv4地址的用户而言&#xff0c;他们主要靠回收和未使用地址段的释放才能用上IPv4&#xff0c;其中这些地址要么来自倒闭的组织&#xff0c;要么来自于那些已经迁移到IPv6时不再需要的地址。 不难想象&#xff0c;获取日益稀缺的IPv4中间过程变得复杂&…

Python 第四十三章 MYSQL 补充

多表查询 1.笛卡尔积:将两表所有的数据一一对应,生成一张大表 select * from dep,emp; #两个表拼一起 select * from dep,emp where dep.id emp.dep_id; #找到两表之间对应的关系记录 select * from dep,emp where dep.id emp.dep_id and dep.name技术; #筛选部门名称为技…

web架构师编辑器内容-快捷键操作的实现

快捷键操作的需求 元素选择 前提都是在元素被选中的情况下 拷贝图层 - ⌘C / CtrlC &#xff1a; 新建当前选择的元素的一个数据结构粘贴图层 - ⌘V / CtrlV &#xff1a; 将新建的元素添加到 components 数组中删除图层 - Backspace / Delete &#xff1a; 在 components 数…

接口测试之webservice

什么是Webservice Web service是一个平台独立的&#xff0c;低耦合的&#xff0c;自包含的、基于可编程的web的应用程序&#xff0c;可使用开放的XML&#xff08;标准通用标记语言下的一个子集&#xff09;标准来描述、发布、发现、协调和配置这些应用程序&#xff0c;用于开发…

STL之map【有序哈希表】使用方法

这里写目录标题 map【有序哈希表】使用方法1.头文件:2.创建map:3.添加键值对:4.查找键值对&#xff1a;5.遍历键-值对&#xff1a;5.综合示例&#xff1a;班级学生 map【有序哈希表】使用方法 话不多说&#xff0c;接着讲map用法&#xff1a; map&#xff1a;映射&#xff0c…