其他分享
首页 > 其他分享> > 手写@Async异步注解

手写@Async异步注解

作者:互联网

一、自定义注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CopyAsync {
}

二、编写AOP切面类

@Aspect
@Component
public class CopyAsyncAop {
    @Around(value = "@annotation(com.xx.CopyAsync)")
    public void around(ProceedingJoinPoint joinPoint) {
        try {
            // 一般使用线程池
            new Thread(() -> {
                try {
                    joinPoint.proceed();
                } catch (Throwable throwable) {
                    throwable.printStackTrace();
                }
            }, "线程xx").start();

        } catch (Throwable throwable) {

        }

    }
}

三、调用测试类

@RestController
@Slf4j
public class Test {
    @Autowired
    private TestService testService;

    @RequestMapping("/add")
    public String add() {
        log.info("1");
        testService.asyncLog();
        log.info("3");
        return "3";
    }
}

四、TestService类

@Component
@Slf4j
public class TestService {
    @CopyAsync
    public void asyncLog() {
        try {
            log.info("目标方法开始执行,阻塞10秒");
            Thread.sleep(10000);
            log.info("2");
        } catch (Exception e) {
        }

    }
}

标签:info,异步,log,CopyAsync,throwable,catch,Async,手写,public
来源: https://www.cnblogs.com/LoveShare/p/16398612.html