Request传递到异步线程里的坑
测试用例
@GetMapping("/getTest")
public String getTest(HttpServletRequest request, HttpServletResponse response) {
String age = request.getParameter("age");
System.out.println("age=" + age);
new Thread(() -> {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
String age1 = request.getParameter("age");
System.out.println("age1=" + age1);
}).start();
return "success";
}
浏览器输入
http://127.0.1:8080/getTest?age=18
控制台会打印
为什么异步线程中获取到的age=null???
我们再次在浏览器输入
http://127.0.1:8080/getTest?age=18
会发现我们程序接收不到age=18
说明两次请求使用的是同一个Request,Request被复用了
从调用链接的角度来说,虽然我们调用的是这个链接:
http://127.0.1:8080/getTest?age=18
但是对于程序来说,它等效于这个链接:
http://127.0.1:8080/getTest
原因
链接: https://segmentfault.com/a/1190000042184829
解决
需要使用到Request的异步编程
@GetMapping("/getTest")
public String getTest(HttpServletRequest request, HttpServletResponse response) {
AsyncContext asyncContext = request.startAsync(request, response);
String age = request.getParameter("age");
System.out.println("age=" + age);
new Thread(() -> {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
String age1 = request.getParameter("age");
System.out.println("age1=" + age1);
asyncContext.complete();
}).start();
return "success";
}
完美解决