Asynchronous Java annotations @Async trap

  Perhaps you would like this process when adding asynchronous Java back-end process, then shook her put on a large, dingy flash, and the actual operating result was not what we expect. So, now the test results will be recorded as follows, for detours.

  (A) adding annotations @Async Controller directly exposed interface layer

  Will immediately end the current call to end the kinds of interfaces, namely means the beginning of the end, does not care about the data returned by the asynchronous interface, in fact, this interface is only suitable for commanding at the front end, regardless of the follow-up to back-end process flow, and do not need returned by the backend object.

  (B) add annotations directly @Async private interface Controller layer

  This situation is, call the back end of the front end of the public interface of the interface and wait for returns, this time calling the layer adds private methods @Async annotation in the interface, you might expect is for the back-end interface to return immediately, so specific processes in @Async annotation private function may be the fact that you did not achieve the effect, add a private @Async annotation function is still the synchronization process, even if you add @EnableAsync notes in front of the class Controller layer, It does not help; so, in this way reach the asynchronous results. We can verify that the procedure through the log, as shown below:

  In the figure above, we see first enter the Controller layer to expose an interface, and then enter the private methods annotated with @Async, then jumped out, and finally back to the Controller layer to expose an interface, the entire process is the synchronization process, this time @Async comment no effect.

  (C) @Async add annotations directly in the public interface layer Service

  Provide synchronous process in the Controller layer interface, but in this layer calls the asynchronous interface Service layer, just add annotations to @Async above the interface needs to complete the task with asynchronous process, this strategy can achieve our asynchronous process, we verified that the flow through the log, as shown below:

  In the figure above, we see the process first enter the Controller layer, then immediately jumped out of the Controller layer, and an asynchronous interface Service layer is the follow-up tasks, and this process has reached an asynchronous process we want.

 

------ 20,200,116 Mian

Guess you like

Origin www.cnblogs.com/bien94/p/12202851.html
Recommended