As the first ruthless person of liao North OF me, there are naturally a few code battle is my flagship

However, when receiving the callback request from the enterprise wechat, I encountered a problem.

Enterprises WeChat callback request must be within 5 seconds to the appropriate, but the business code there is complex, there are a lot of calls between various micro service relationship, may not end in 5 seconds, while the enterprise WeChat will resend the request, but the callback does not need corresponding returns, so I naturally think of using asynchronous method calls, While making it sure that my method senses the start of the enterprise wechat callback, I can also return a fixed response directly. Naturally, I reached for Spring’s @async……

@async: I was so scared

All kidding aside, let’s introduce what asynchronous calls are:

Asynchronous invocation is aimed at the concept of synchronization, code can not be executed one after another – return, but sent the call instructions, the caller does not have to wait for the method called to complete execution; Instead, proceed with the following process. (Multithreading)

In Spring, methods based on the @async annotation are called asynchronous methods. When these methods are executed, they are executed in a separate thread, and the caller can proceed without waiting for it to complete.

It’s easy to make an asynchronous call by slapping @async hard on the method, like this


However, the return of this method will not be used by the call, because before the asynchronous method is finished, the call has already returned the request to wechat. If we need the return value of this asynchronous method, we should wrap the return value with Future<>

Ps: Future is an interface that can query objects of type runnable and Callable to complete, cancel, end, and retrieve results

And Spring implements a subclass of it: Async<>, which is returned by @async decorated methods

The caller can also use isDone to determine whether the asynchronous method has completed execution, which is the usual way to play


So there must be a child to ask, that you this asynchronous method in the exception how to do? How does an exception get thrown?

It also scored case, if it is a void method, you’ll have to write a configuration class, realize AsyncConfigurer then override getAsyncUncaughtException method Then write a Handler, exception handling in it.

If it’s a method that returns a value, you can try the catch at the call

That’s enough for me for now, and I’ll have a good look at the implementation after this iteration.

Reference blog:

www.cnblogs.com/jpfss/p/102…

Cloud.tencent.com/developer/a…

www.jianshu.com/p/11c787177…