当前位置: 代码网 > it编程>编程语言>Java > SpringBoot中使用异步线程导致Request请求头丢失问题的解决方法

SpringBoot中使用异步线程导致Request请求头丢失问题的解决方法

2025年07月23日 Java 我要评论
背景异步线程请求头丢失的问题通常发生在多线程环境中,特别是在使用 completablefuture 或其他异步编程模型时。具体原因如下:异步线程请求头丢失的原因当主线程将任务提交到异步线程池执行时,

背景

异步线程请求头丢失的问题通常发生在多线程环境中,特别是在使用 completablefuture 或其他异步编程模型时。具体原因如下:

异步线程请求头丢失的原因

当主线程将任务提交到异步线程池执行时,当前线程中的 requestattributes(包括请求头等上下文信息)不会自动传递到异步线程中。这是因为 requestattributes 是基于当前线程的本地存储(threadlocal)实现的,而异步线程是在不同的线程中执行任务,因此无法访问到主线程中的 requestattributes。这种情况下,异步线程执行任务时会丢失请求头等上下文信息。
为了确保异步线程能够正确获取请求上下文信息,需要在任务执行前后显式地设置和重置 requestattributes。

一、问题描述

笔者在开发中使用completablefuture去异步调用openfegin服务,但是在传递过程中发现了问题,原来存储在header中的信息,在进入其他服务后header中存储的user信息都丢失了

completablefuture<r<boolean>> ordercheckfuture = completablefuture.supplyasync(() -> remotebusinessservice.checkunfinishedorder(securityconstants.inner, userid));
completablefuture<r<boolean>> taskcheckfuture = completablefuture.supplyasync(() -> remoteinspectionservice.checkunfinishedtask(securityconstants.inner, userid));
completablefuture.allof(ordercheckfuture, taskcheckfuture).join();
r<boolean> ordercheck = ordercheckfuture.join();
r<boolean> taskcheck = taskcheckfuture.join();

这种写法就导致了请求头信息丢失,服务调用的发起方在system服务模块,header中的租户id为12361

请求在到达business服务模块或者inspection服务模块时,租户id丢失,变成了默认值9999

二、解决方案

requestattributes requestattributes = requestcontextholder.getrequestattributes();

completablefuture<r<boolean>> ordercheckfuture = completablefuture.supplyasync(() -> {
    requestcontextholder.setrequestattributes(requestattributes);
    return remotebusinessservice.checkunfinishedorder(securityconstants.inner, userid);
});

completablefuture<r<boolean>> taskcheckfuture = completablefuture.supplyasync(() -> {
    requestcontextholder.setrequestattributes(requestattributes);
    return remoteinspectionservice.checkunfinishedtask(securityconstants.inner, userid);
});

completablefuture.allof(ordercheckfuture, taskcheckfuture).join();

r<boolean> ordercheck = ordercheckfuture.join();
r<boolean> taskcheck = taskcheckfuture.join();

先通过如下代码获取请求头属性

requestattributes requestattributes = requestcontextholder.getrequestattributes();

接着在异步线程中重新设置下异步线程所携带请求头的信息,这样就保证了请求头的连续传递性

三、拓展

不想每次都在completablefuture中都写如下设置请求头信息的代码怎么办?

requestcontextholder.setrequestattributes(requestattributes);

笔者这里给出一个自认为相对能减少点代码量的解决方法(具体有无必要完全看个人)

自定义一个继承completablefuture的类 customcompletablefuture

package com.zlbc.common.core.async;

import org.springframework.web.context.request.requestcontextholder;
import org.springframework.web.context.request.requestattributes;

import java.util.concurrent.completablefuture;
import java.util.concurrent.executor;
import java.util.function.supplier;

/**
 * @author hulei
 * 异步线程传递请求头,跨服务调用时需要传递请求头信息
 */
public class customcompletablefuture<t> extends completablefuture<t> {

    public static <t> customcompletablefuture<t> supplyasync(supplier<t> supplier, executor executor, requestattributes requestattributes) {
        customcompletablefuture<t> future = new customcompletablefuture<>();
        executor.execute(() -> {
            try {
                requestcontextholder.setrequestattributes(requestattributes);
                t result = supplier.get();
                future.complete(result);
            } catch (exception e) {
                future.completeexceptionally(e);
            } finally {
                requestcontextholder.resetrequestattributes();
            }
        });
        return future;
    }

    public static customcompletablefuture<void> runasync(runnable runnable, executor executor, requestattributes requestattributes) {
        customcompletablefuture<void> future = new customcompletablefuture<>();
        executor.execute(() -> {
            try {
                requestcontextholder.setrequestattributes(requestattributes);
                runnable.run();
                future.complete(null);
            } catch (exception e) {
                future.completeexceptionally(e);
            } finally {
                requestcontextholder.resetrequestattributes();
            }
        });
        return future;
    }
}


使用方法如下,笔者设置了一个可以传递线程池的参数

requestattributes requestattributes = requestcontextholder.getrequestattributes();
        
executorservice customexecutor = executors.newfixedthreadpool(5);
        
customcompletablefuture<r<boolean>> ordercheckfuture = customcompletablefuture.supplyasync(
                () -> remotebusinessservice.checkunfinishedorder(securityconstants.inner, userid),
                customexecutor,
                requestattributes
);

customcompletablefuture<r<boolean>> taskcheckfuture = customcompletablefuture.supplyasync(
                () -> remoteinspectionservice.checkunfinishedtask(securityconstants.inner, userid),
                customexecutor,
                requestattributes
);

completablefuture.allof(ordercheckfuture, taskcheckfuture).join();

r<boolean> ordercheck = ordercheckfuture.join();
r<boolean> taskcheck = taskcheckfuture.join();

这种写法就是减少了设置的代码,传一个参数进去即可

requestattributes requestattributes = requestcontextholder.getrequestattributes();

这个可以写在某些全局工具类如servletutils

使用时如下获取即可

requestattributes requestattributes = servletutils.getrequestattributes();

四、总结

本篇文章主要描述了笔者实际开发中遇到的采用异步线程导致请求头丢失的问题,本文详细介绍了问题发生的场景和解决方法。实际可以从以下几个方面考虑

  1. 显式传递 requestattributes:
  • 在异步任务执行前,获取当前线程的 requestattributes。
  • 在异步任务执行时,显式地设置 requestattributes。
  • 在异步任务执行后,重置 requestattributes,以避免影响后续任务。
  1. 使用自定义 completablefuture 实现:
  • 创建一个自定义的 completablefuture 实现,在任务执行前后自动设置和重置 requestattributes。
  • 这样可以确保每个异步任务都能访问到正确的请求上下文信息。
  1. 使用 threadlocal 传递上下文信息:
  • 利用 threadlocal 将请求上下文信息(如请求头等)封装在一个对象中。
  • 在异步任务执行前后,显式地传递并设置这个对象。
  1. 使用 aop(面向切面编程):
  • 通过 aop 在方法调用前后自动设置和重置 requestattributes。
  • 这样可以减少手动设置和重置 requestattributes 的代码量。
  1. 使用 spring 提供的工具类:
  • 利用 spring 提供的工具类(如 requestcontextholder 和 requestattributes)来管理请求上下文。
  • 在异步任务执行前后,显式地设置和重置这些工具类的状态。

通过上述方法,可以确保异步线程在执行任务时能够正确访问到请求上下文信息,从而避免请求头丢失的问题。对您有帮助的话,请关注点赞支持一波哦!

以上就是springboot中使用异步线程导致request请求头丢失问题的解决方法的详细内容,更多关于springboot request请求头丢失的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com