项目使用@Async注解进行异步请求,获取RequestAttributes为空,后续操作中从request获取参数报错,后查询资料解决;

方法一:异步之前开启子线程共享
设置值:
ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
sra.setAttribute("key","value",1);//设置参数值
RequestContextHolder.setRequestAttributes(sra, true);//设置子线程共享取值:
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if(attributes != null) {
String value = attributes.getAttribute("key", 1);
}结果:本地idea测试通过,部署到服务器后失效,原因未深究,使用了方法二。
方法二:使用 ThreadLocal传递参数
Threadlocal是一个线程内部的存储类,可以在指定线程内存储数据,数据存储以后,只有指定线程可以得到存储数据
设置值:异步方法传入参数,将参数设置到ThreadLocalUtil中
@Async
public void testAsyn(String name) {
ThreadLocalUtil.set("name", name);
// .......
}取值:在异步方法中获取参数
String ThreadLocalUtil.get("name");结果:解决问题
附带ThreadLocalUtil工具类代码:https://blog.csdn.net/weixin_42260124/article/details/118763029
版权声明:本文为weixin_42260124原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。