<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
@RestController @Slf4j public class Thread04 { @Autowired private OrderManage orderManage; @GetMapping("addOrder") public String addOrder(){ log.info("1"); //异步处理 orderManage.asyncLog(); log.info("3"); log.info(Thread.currentThread().getName()+"线程执行结束"); return "5"; } }
@Component @Slf4j public class OrderManage { //@Async @MyAsyncAnnotation//自定义的注解 public void asyncLog(){ log.info("目标方法执行开始"); try { Thread.sleep(3000); } catch (InterruptedException e) { throw new RuntimeException(e); } log.info(Thread.currentThread().getName()+"子线程执行结束"); } }
注解
import java.lang.annotation.*; @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface MyAsyncAnnotation { }
切面
import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; @Component @Aspect @Slf4j public class ThreadAsyncAop { /** * 环绕通知,拦截方法 * * @param joinPoint * @return */ @Around(value = "@annotation(boot.annotation.MyAsyncAnnotation)") public void around(ProceedingJoinPoint joinPoint) { log.info("环绕通知执行开始"); new Thread(() -> { try { joinPoint.proceed();//目标方法--asyncLog() } catch (Throwable e) { throw new RuntimeException(e); } }).start(); log.info("环绕通知执行结束"); } }
标签:info,异步,log,自定义,org,annotation,import,注解,public From: https://www.cnblogs.com/ixtao/p/17455963.html