Spring/Spring boot项目接入traceId

这篇具有很好参考价值的文章主要介绍了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);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute("startTime", System.currentTimeMillis());
        //traceOrigin、traceCaller、traceId
        String 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 {
            //设置MDC
            MDC.put(TraceConstants.LOG_TRACE_ORIGIN, traceOrigin);
            MDC.put(TraceConstants.LOG_TRACE_CALLER, traceCaller);
            MDC.put(TraceConstants.LOG_TRACE_ID, traceId);
        }

        //IP
        String 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);
    }

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

    @Bean
    public TraceWebInterceptor traceWebInterceptor() {
        return new TraceWebInterceptor();
    }

    @Override
    public 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);
        }

        @Override
        public void execute(Runnable task) {
            super.execute(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));
        }

        @Override
        public <T> Future<T> submit(Runnable task, T result) {
            return super.submit(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), result);
        }

        @Override
        public <T> Future<T> submit(Callable<T> task) {
            return super.submit(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));
        }

        @Override
        public 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);
        }

        @Override
        public void execute(Runnable task) {
            super.execute(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));
        }

        @Override
        public <T> ForkJoinTask<T> submit(Runnable task, T result) {
            return super.submit(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), result);
        }

        @Override
        public <T> ForkJoinTask<T> submit(Callable<T> task) {
            return super.submit(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));
        }
    }
}

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

@Configuration
public class TaskExecutorConfig {

    @Bean
    public 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 {

        @Override
        public void execute(Runnable task) {
            super.execute(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));
        }

        @Override
        public void execute(Runnable task, long startTimeout) {
            super.execute(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), startTimeout);
        }

        @Override
        public <T> Future<T> submit(Callable<T> task) {
            return super.submit(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));
        }

        @Override
        public Future<?> submit(Runnable task) {
            return super.submit(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));
        }

        @Override
        public ListenableFuture<?> submitListenable(Runnable task) {
            return super.submitListenable(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));
        }

        @Override
        public <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);
        }

        @Override
        protected <V> RunnableScheduledFuture<V> decorateTask(Callable<V> callable, RunnableScheduledFuture<V> task) {
            return super.decorateTask(WrapUtil.wrap(callable, MDC.getCopyOfContextMap()), task);
        }

        @Override
        protected <V> RunnableScheduledFuture<V> decorateTask(Runnable runnable, RunnableScheduledFuture<V> task) {
            return super.decorateTask(WrapUtil.wrap(runnable, MDC.getCopyOfContextMap()), task);
        }

        @Override
        public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
            return super.schedule(WrapUtil.wrap(command, MDC.getCopyOfContextMap()), delay, unit);
        }

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

        @Override
        public ScheduledFuture<?> schedule(Runnable task, Date startTime) {
            return super.schedule(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), startTime);
        }

        @Override
        public ScheduledFuture<?> schedule(Runnable task, Trigger trigger) {
            return super.schedule(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), trigger);
        }

        @Override
        public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) {
            return super.scheduleAtFixedRate(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), period);
        }

        @Override
        public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period) {
            return super.scheduleAtFixedRate(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), startTime, period);
        }

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

        @Override
        public void execute(Runnable task) {
            super.execute(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));
        }

        @Override
        public void execute(Runnable task, long startTimeout) {
            super.execute(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), startTimeout);
        }

        @Override
        public <T> Future<T> submit(Callable<T> task) {
            return super.submit(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));
        }

        @Override
        public Future<?> submit(Runnable task) {
            return super.submit(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));
        }

        @Override
        public ListenableFuture<?> submitListenable(Runnable task) {
            return super.submitListenable(WrapUtil.wrap(task, MDC.getCopyOfContextMap()));
        }

        @Override
        public <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);
        }

        @Override
        protected <V> RunnableScheduledFuture<V> decorateTask(Callable<V> callable, RunnableScheduledFuture<V> task) {
            return super.decorateTask(WrapUtil.wrap(callable, MDC.getCopyOfContextMap()), task);
        }

        @Override
        protected <V> RunnableScheduledFuture<V> decorateTask(Runnable runnable, RunnableScheduledFuture<V> task) {
            return super.decorateTask(WrapUtil.wrap(runnable, MDC.getCopyOfContextMap()), task);
        }

        @Override
        public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
            return super.schedule(WrapUtil.wrap(command, MDC.getCopyOfContextMap()), delay, unit);
        }

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

        @Override
        public ScheduledFuture<?> schedule(Runnable task, Date startTime) {
            return super.schedule(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), startTime);
        }

        @Override
        public ScheduledFuture<?> schedule(Runnable task, Trigger trigger) {
            return super.schedule(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), trigger);
        }

        @Override
        public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) {
            return super.scheduleAtFixedRate(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), period);
        }

        @Override
        public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period) {
            return super.scheduleAtFixedRate(WrapUtil.wrap(task, MDC.getCopyOfContextMap()), startTime, period);
        }

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

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

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        //traceOrigin、traceCaller、traceId
        String 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 {
            //设置MDC
            MDC.put(TraceConstants.LOG_TRACE_ORIGIN, traceOrigin);
            MDC.put(TraceConstants.LOG_TRACE_CALLER, traceCaller);
            MDC.put(TraceConstants.LOG_TRACE_ID, traceId);
        }

        //IP
        String 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);

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

    @Override
    public void onAcknowledgement(RecordMetadata metadata, Exception exception) {
    }

    @Override
    public void close() {
    }

    @Override
    public void configure(Map<String, ?> configs) {
    }
}

2.6 线程池使用步骤

替换ThreadPoolExecutor为包装类文章来源地址https://www.toymoban.com/news/detail-820907.html

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

到了这里,关于Spring/Spring boot项目接入traceId的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【Java开发】 Spring 11 :Spring Boot 项目部署至云服务器

    Spring Boot 项目开发结束后的工作便是运维,简单来说需要配置 Web 运行参数和项目部署两大工作,本文将尽可能详细地给大家讲全! 目录 1 定制 Web 容器运行参数 1.1 运行参数介绍 1.2 项目搭建 ① 通过 IDEA Spring Initializr 创建项目 ② 添加 Spring Web 等依赖 ③ 编写 controller 层的

    2023年04月23日
    浏览(60)
  • Spring Boot集成Spring AI实现快速接入openAI

    Spring AI API 涵盖了广泛的功能。每个主要功能都在其专门的部分中进行了详细介绍。为了提供概述,可以使用以下关键功能: 跨 AI 提供商的可移植 API,用于聊天、文本到图像和嵌入模型。支持同步和流 API 选项。还支持下拉访问模型特定功能。我们支持 OpenAI、Microsoft、Amaz

    2024年04月28日
    浏览(34)
  • 网页版Java(Spring/Spring Boot/Spring MVC)五子棋项目(四)对战模块

    匹配成功返回数据 1. message消息类别 2. ok 3. reson 4. 房间id 5. 双方id 6.白色玩家 一个类记录房间中的信息(房间id,两个用户id,是否为白棋) 信息提示框 处理匹配API 初始化游戏(棋盘,下一个棋子,接受棋子处理响应,判断是否结束) 1. 客户端连接到游戏房间后, 服务器返回

    2024年02月13日
    浏览(52)
  • Spring boot项目java bean和xml互转

    工作中需要给下游第三方收费系统做数据挡板,由于下游系统使用的是 soap webservice ,里面涉及各种xml跟bean的互转,在此介绍一下使用的方法。 基于springboot搭建webservice的过程将会在下篇博客介绍 这里介绍两种方法. 使用 jackson 进行互转, Spring boot 项目自带的 json 和 bean 的互

    2024年01月19日
    浏览(50)
  • Java(二):Spring Boot 项目-文件的增删改查下载

    docker运行mysql 设置MySQL时区 添加修改 /mysql/conf.d/xxx.cnf 文件,并重启 MySQL 查看当前MySQL使用的时区 MySQL建库建表 数据表实体类 注意: 规定参数时区 com/example/user/entity/FileTable.java 查询条件实体类 com/example/user/entity/FileTableCondition.java com/example/user/utils/FileUtil.java mapper user/src/mai

    2024年02月09日
    浏览(54)
  • Java spring-boot项目中如何上传下载文件或图片到spring-boot规定的非静态目录

    spring-boot的项目,虽然它自己定义了一个静态文件的存储目录,但是这个目录一般是作为前端静态文件的目录来作为使用的。如果使用这个静态目录来作为我们上传文件的目录会有一个比较尴尬的地方:将spring-boot打包成为jar包后,随着上传图片的增多,这个jar包也会跟着变大

    2024年02月16日
    浏览(58)
  • java 配置打包Spring Boot项目过程中跳过测试环节

    上文 java 打包Spring Boot项目,并运行在windows系统中中 我们演示了打包 Spring Boot项目的并运行在本地的方法 但是 我们这里会看到 每次打包 他这都会有个T E S T S 测试的部分 但是 我们自己开发的程序 要上线 有没有问题我们肯定自己清楚啊 没必要它做测试 而且有些程序走这个

    2024年02月13日
    浏览(50)
  • idea创建spring boot项目,java版本只能选择17和21

    java版本为\\\"11.0.20\\\",idea2023创建spring boot项目时(File-Project-Spring Initializr),java版本无法选择11,导致报错,如下图所示: spring2.X版本在2023年11月24日停止维护了,因此创建spring项目时不再有2.X版本的选项,只能从3.1.X版本开始选择 而Spring3.X版本不支持JDK8,JDK11,最低支持JDK1

    2024年02月05日
    浏览(65)
  • 如何通过IDEA创建基于Java8的Spring Boot项目

    上次发现我的 IDEA 创建 Spring Boot 项目时只支持 11 和 17 的 JDK 版本,于是就通过Maven搭建SpringBoot项目。 究其原因,原来是Spring官方抛弃了Java8!!! 使用IDEA内置的Spring Initializr创建SpringBoot项目时,已经没有了Java8的选项,只支持 = 17的版本: 网上逛了一圈,原来是Spring Boot官

    2024年01月19日
    浏览(56)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包