写一个接口,用于测试:
import cn.hutool.core.thread.AsyncUtil;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.CompletableFuture;
@RestController
@RequestMapping("test")
public class TestController {
@Resource
private HttpServletRequest request;
@GetMapping("request")
public String request() {
AsyncUtil.get(CompletableFuture.runAsync(() -> {
String id = request.getParameter("id");
System.out.println(id);
}));
AsyncUtil.get(CompletableFuture.runAsync(() -> {
String id = request.getParameter("id");
System.out.println(id);
}));
return "";
}
}
我们请求一下
发现抛出了异常
我们在第一行加上这行代码:
RequestContextHolder.setRequestAttributes(RequestContextHolder.getRequestAttributes(), true);
成功获取
尝试将这行代码放入拦截器,也成功生效
这是因为源码中,如果我们传入inheritable
为true
,则在NamedInheritableThreadLocal
中设置值
该类继承了InheritableThreadLocal
,因此可以在子线程共享变量
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有