Home > Back-end >  Java multi-thread calls request header is missing
Java multi-thread calls request header is missing

Time:05-08

1. By the method of the main thread calls the m1, request header, sra is not null
2. The other one thread calls the m1 method, lost the request header, sra is null, the Internet to find a lot of methods, basic it is such a set, why I can't,


@ PostMapping (value="https://bbs.csdn.net/test")
Public String postTest (it request, @ RequestBody Stu Stu) {
The ExecutorService exe=Executors. NewSingleThreadExecutor ();
TestService TestService=new TestService ();
TestService. M1 ();
ServletRequestAttributes sra=(ServletRequestAttributes) RequestContextHolder. GetRequestAttributes ();
RequestContextHolder. SetRequestAttributes (sra, true);
CompletableFuture. RunAsync (() - & gt; {
TestService. M1 ();
}, exe);
Return "11";
}

The class TestService {
Int (m1) {
ServletRequestAttributes sra=(ServletRequestAttributes) RequestContextHolder. GetRequestAttributes ();
Try {//simulate remote call takes 5 seconds
TimeUnit. SECONDS. Sleep (5);
{} catch InterruptedException (e)
e.printStackTrace();
}
return 1;
}
}

CodePudding user response:

Asynchronous invocation, sra has not been initialized successfully, so the value is null
  • Related