How to handwrite an @Async asynchronous annotation
1. Custom annotations
Customize a @MyAsync annotation, you can copy @Async
@Target({
ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAsync {
}
2. Write AOP aspect classes
@Aspect
@Component
public class MyAsyncAop {
@Around(value = "@annotation(org.sang.annotation.MyAsync)")
public Object around(ProceedingJoinPoint joinPoint) {
try {
System.out.println("环绕通知开始执行--");
new Thread(() -> {
try {
joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}).start();
System.out.println("环绕通知结束执行--");
} catch (Exception e) {
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return null;
}
}
3. Write test classes
controller class:
@RequestMapping("/mysync")
public String mysync(){
System.out.println("-------------<1>--------------");
this.userService.asnycLog();
System.out.println("-------------<3>--------------");
return "success";
}
service class:
@MyAsync
public void asnycLog() {
try {
System.out.println("目标方法开始执行,正在阻塞3s----");
Thread.sleep(3000);
System.out.println("-------------<2>--------------");
}catch (Exception e){
}
}
Local access:
The print result is as follows:
-------------<1>--------------
环绕通知开始执行--
环绕通知结束执行--
-------------<3>--------------
目标方法开始执行,正在阻塞3s----
-------------<2>--------------
4. Summary
As can be seen from the above print log, when the asnycLog() method of the service is called from the controller, because the asnycLog() method has the @MyAsync annotation, and the @MyAsync annotation has a surrounding notification defined in the aop, a new child thread is started. Execution, so there is no need to wait for the main thread to execute, thus achieving asynchronous execution. Therefore, the execution of the main thread is completed, the execution of the sub-thread is finally completed, and the program execution through the method annotated with @MyAsync is executed asynchronously.