栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java.lang.IllegalStateException: No thread-bound request found 解决方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java.lang.IllegalStateException: No thread-bound request found 解决方法

1、让我们看看这熟悉的报错
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.
2、我的使用场景

在@Async注解的方法里进行Feign调用,为什么会出现这个问题尼?是因为我@configurtion里加了这行代码,因为有业务需求我要从request里取到header里的参数

HttpServletRequest request = ((ServletRequestAttributes) 
(RequestContextHolder.currentRequestAttributes())).getRequest();
3、那这个报错信息从何而来?

点进RequestContextHolder这个类,查看源码可知,RequestAttributes - 请求属性线程拿不到了,所以为null,然后就throw new IllegalStateException,以下为源码:

	
	public static RequestAttributes currentRequestAttributes() throws IllegalStateException {
		RequestAttributes attributes = getRequestAttributes();
		if (attributes == null) {
			if (jsfPresent) {
				attributes = FacesRequestAttributesFactory.getFacesRequestAttributes();
			}
			if (attributes == null) {
				throw new 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.");
			}
		}
		return attributes;
	}
4、解决方法

只需要在调用异步方法的外面将RequestAttributes对象设置为子线程共享即可

4.2、核心代码
ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
RequestContextHolder.setRequestAttributes(sra, true);
4.3、举个栗子
public void childThreadSharing(ScreeningDTO dto) {
	// 设置子线程共享
	ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    RequestContextHolder.setRequestAttributes(sra, true);
	// 开始执行异步方法
	this.somethingService.executeAsync();
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/759614.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号