解决异常:Spring 异步任务操作请求对象报错 No thread-bound request found

2025-02-10后端2 分钟309 次阅读
AI 摘要salmon-ai

本文详细解析了 Spring 异步任务中访问 HttpSer

问题

在对某个接口进行异步优化时,遇到了如下异常:

bash 复制代码
java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
	at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
	at org.springframework.web.context.support.WebApplicationContextUtils.currentRequestAttributes(WebApplicationContextUtils.java:313)
	at org.springframework.web.context.support.WebApplicationContextUtils.access$400(WebApplicationContextUtils.java:66)
	at org.springframework.web.context.support.WebApplicationContextUtils$RequestObjectFactory.getObject(WebApplicationContextUtils.java:329)
	at org.springframework.web.context.support.WebApplicationContextUtils$RequestObjectFactory.getObject(WebApplicationContextUtils.java:324)
	at org.springframework.beans.factory.support.AutowireUtils$ObjectFactoryDelegatingInvocationHandler.invoke(AutowireUtils.java:292)
	at jdk.proxy2/jdk.proxy2.$Proxy149.getHeader(Unknown Source)
	at com.salmon.blogservice.utils.IpUtils.getIpAddress(IpUtils.java:35)
	at com.salmon.blogservice.service.impl.BlogInfoServiceImpl.report(BlogInfoServiceImpl.java:153)
	at com.salmon.blogservice.controller.BlogInfoController.lambda$report$0(BlogInfoController.java:155)
	at com.alibaba.ttl.TtlRunnable.run(TtlRunnable.java:60)
	at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:539)
	at java.base/java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:264)
	at java.base/java.util.concurrent.FutureTask.run(FutureTask.java)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
	at java.base/java.lang.Thread.run(Thread.java:833)

其实这个问题报错后,一下子就能想到应该是线程上下文相关的问题,而这个问题是:在异步线程中需要访问主线程中的 HttpServletRequest 对象时,由于异步线程没有绑定到当前的 HTTP 请求,导致请求上下文无法被正确传递。

示例代码

为了复现问题,我这里举例下代码,如下:

java 复制代码
@RestController
@AllArgsConstructor
public class TestController {

    private TestService testService;
    private ExecutorService executorService;

    @PostMapping("/test1")
    public Result<?> test1() {
        executorService.submit(() -> {
            testService.test1();
        });
        return Result.ok();
    }
}

@Service
@Slf4j
@AllArgsConstructor
public class TestServiceImpl implements TestService {

    private HttpServletRequest request;

    @Override
    public void report() {
        String ipAddress = IpUtils.getIpAddress(request);
        log.info("ipAddress: {}", ipAddress);
    }
}

调用接口可以看到这个错误
image.png
当我们通过工具调用接口时,便会看到上面所提到的异常。通过 Debug 与分析,我们可以确定,这个问题的根源在于异步线程无法访问主线程中的 request 对象。

解决方法

Spring 提供了 RequestContextHolder 类,用于在不同的线程之间传递请求上下文。我们可以在主线程中获取当前的请求上下文,并在异步任务中手动设置它。

代码如下:

java 复制代码
@PostMapping("/test1")
public Result<?> test1() {
    // 获取当前主线程的请求上下文
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    executorService.submit(() -> {
        // 在异步线程中设置请求上下文
        RequestContextHolder.setRequestAttributes(requestAttributes);
        // 执行业务逻辑
        testService.test1();
        // 任务完成后,清除请求上下文
        RequestContextHolder.resetRequestAttributes();
    });
    return Result.ok();
}

总结

在处理 Spring 异步任务时,如果需要在后台线程中访问请求上下文(如 HttpServletRequest),我们需要确保请求上下文能够在异步线程中正确传递,在我这个问题中,通过 RequestContextHolder 可以轻松实现主线程请求上下文的传递。

觉得有用就点个赞,不用登录也能读

评论

0 条
登录 之后才能评论
—
还没有评论,来说第一句