java 在使用多线程时,调用其他服务的接口返回403,RequestAttributes为null

我们按以下步骤分析原因:

  • 第一点,返回403说明调用接口时未经授权
  • 第二点,若后端主线程中发现Request Header已经带着从前端发送的Authentication和接口参数,并且在子线程调用其他服务接口日志中打印获取RequestContextHolder.currentRequestAttributes为null

以上问题说明在调用接口服务时请求头信息丢失(Authentication),导致授权失败,调接口失败
我们去看下RequestContextHolder这个类的源代码,会发现问题

private static final ThreadLocal<RequestAttributes> requestAttributesHolder =
			new NamedThreadLocal<>("Request attributes");

	private static final ThreadLocal<RequestAttributes> inheritableRequestAttributesHolder =
			new NamedInheritableThreadLocal<>("Request context");


	public static void setRequestAttributes(@Nullable RequestAttributes attributes, boolean inheritable) {
		if (attributes == null) {
			resetRequestAttributes();
		}
		else {
			if (inheritable) {
				inheritableRequestAttributesHolder.set(attributes);
				requestAttributesHolder.remove();
			}
			else {
				requestAttributesHolder.set(attributes);
				inheritableRequestAttributesHolder.remove();
			}
		}

源码解析

  1. List itemrequestAttributesHolder 是NamedThreadLocal对象,NamedThreadLocal继承ThreadLocal,用于存储数据,可保证线程之间数据的隔离,只允许当前线程获取到存入的值,所以不难理解,这就是子线程未获取到请求头信息的原因。
  2. 再注意inheritableRequestAttributesHolder 这个变量和setRequestAttributes方法,inheritableRequestAttributesHolder 对象类型是NamedInheritableThreadLocal ,继承InheritableThreadLocal,InheritableThreadLocal是用于线程之间数据共享的,而setRequestAttributes这个方法参数RequestAttributes 就是请求头信息,inheritable是boolean ,意思是是否共享,再看方法里的代码逻辑,如果要保证RequestAttributes 共享,则inheritable设置为true
  3. 因此,在主线程中我们只需要加上下面这行代码,问题迎刃而解。
RequestContextHolder.setRequestAttributes(RequestContextHolder.getRequestAttributes(),true);

或者

RequestContextHolder.setRequestAttributes(RequestContextHolder.currentRequestAttributes(),true);

到这里,这个问题就解决完毕,如果你也遇到过这样的问题,快拿去试试吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

番茄辣酱魂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值