Home  >  Article  >  Java  >  How Springboot uses Aop capture annotations to implement business asynchronous execution

How Springboot uses Aop capture annotations to implement business asynchronous execution

WBOY
WBOYforward
2023-05-23 19:01:041149browse

1. First, let’s talk about several ways to create threads (brief list)

1. Inherit the Thread class and override the run method:

public class ExtendsThread extends Thread{
    @Override
    public void run() {
        try{
            System.out.println(Thread.currentThread().getName()+"执行");
        }catch (Exception e){
 
        }
    }
    public static void main(String[] args) {
        new Thread(new ExtendsThread()).start();
    }
}

2. Implement the Runnable interface and override the run method. Method:

public class ImplementsRunnable implements Runnable{
    @Override
    public void run() {
        try{
            System.out.println(Thread.currentThread().getName()+"执行");
        }catch (Exception e){
 
        }
    }
    public static void main(String[] args) {
        new Thread(new ImplementsRunnable()).start();
        //这里还可以使用匿名内部类的写法创建一个线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+"执行");
            }
        },"匿名内部类实现Runnable接口的线程");
    }
}

3. Implement the Callable interface and use FutureTask to create a thread (you can get the return value):

public class CallableAndFuture implements Callable<String> {
    @Override
    public String call() throws Exception {
        Thread.sleep(3000);
        System.out.println(Thread.currentThread().getName()+"执行");
        return "success";
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<String> futureTask = new FutureTask<>(new CallableAndFuture());
//        futureTask.run();   主线程执行call方法
        new Thread(futureTask).start();
        String result = futureTask.get();
        System.out.println(result);
    }
}

4. Use the thread pool to create a thread (here using the provided thread pool framework Executors to create Thread pool):

public class Executor {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+"执行");
            }
        });
    }
}

2. Let’s talk about the @Async annotation that comes with spring to implement asynchronous tasks

It’s actually very simple, just put the @EnableAsync annotation on the application startup class Enable the use of asynchronous annotations, and then mark @Async on a method of the business class.

@SpringBootApplication
@EnableAsync
public class AopApplication {
    public static void main(String[] args) {
        SpringApplication.run(AopApplication.class, args);
    }
}

Business class method (example):

   @Async
    public void insertDb(){
        /*service code......*/
        System.out.println("2----->收到请求,写入数据库  ");
    }

3. Then let’s design how to use custom annotations to implement asynchronous tasks

First we write an annotation:

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAsync {
    //规定value是异步开关
    boolean value() default false;
}

We set the value of the annotation to a Boolean type, so as to determine the creation of asynchronous threads based on its true or false value.

We put it on the method of the business class:

  @MyAsync(value = true)
    public void deleteDb(){
        /*service code......*/
        System.out.println("delete------>数据删除");
    }

Then we use AOP to scan this annotation:

Aspect
@Component
public class AopUtils {
    @Around(value = "@annotation(com.example.aop.Aop异步.MyAsync)")
    public void listenMyAsync(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        MyAsync annotation = method.getAnnotation(MyAsync.class);
        boolean value = annotation.value();
        if (value)
            new Thread(new Runnable() {
                @SneakyThrows
                @Override
                public void run() {
                    joinPoint.proceed();
                }
            }).start();
        else
            joinPoint.proceed();
    }
}

We can see that we use Around to find the thread for execution After capturing a method stack containing annotations, the corresponding connection point object can be obtained.

Using the getSignture method of the connection point object ProcedJoinPoint to obtain the signature, the signature can be forcibly converted into the method signature MethdSignture type, so that the getMethod method of this type can be used to obtain the method itself, and then the annotations of the method can be obtained. Use the attributes of the annotation to directly obtain the true or false value of the value, thereby determining whether the method is passed synchronously or asynchronously. (The source code utilizes the reflection mechanism).

The above is the detailed content of How Springboot uses Aop capture annotations to implement business asynchronous execution. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete