SpringBoot的Async异步注解及自定义其线程池

开启异步注解(使其生效)

使用@Async注解的时候需要配合@EnableAsync(开启异步注解)

可以在application启动类中使用,使其全局生效,也可以仅仅在当前使用@Async注解的类上使用这个注解
demo

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

此外还可以设置这个异步执行的线程池,更加灵活

新建线程池配置类

package com.boot.common.conf;

import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 线程池配置
 * @author zhh
 *
 */
@Configuration
@EnableAsync
public class ThreadPoolTaskConfig {
    
    

/** 
 *   默认情况下,在创建了线程池后,线程池中的线程数为0,当有任务来之后,就会创建一个线程去执行任务,
 *    当线程池中的线程数目达到corePoolSize后,就会把到达的任务放到缓存队列当中;
 *  当队列满了,就继续创建线程,当线程数量大于等于maxPoolSize后,开始使用拒绝策略拒绝 
 */

    /** 核心线程数(默认线程数) */
    private static final int corePoolSize = 20;
    /** 最大线程数 */
    private static final int maxPoolSize = 100;
    /** 允许线程空闲时间(单位:默认为秒) */
    private static final int keepAliveTime = 10;
    /** 缓冲队列大小 */
    private static final int queueCapacity = 200;
    /** 线程池名前缀 */
    private static final String threadNamePrefix = "Async-Service-";

    @Bean("taskExecutor") // bean的名称,默认为首字母小写的方法名
    public ThreadPoolTaskExecutor taskExecutor(){
    
    
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);   
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveTime);
        executor.setThreadNamePrefix(threadNamePrefix);

        // 线程池对拒绝任务的处理策略
        // CallerRunsPolicy:由调用线程(提交任务的线程)处理该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        executor.initialize();
        return executor;
    }
}

创建两个异步方法的类

第一个类模拟取消订单后发短信

代码中的 @Async("taskExecutor")对应我们自定义线程池中的 @Bean("taskExecutor"),表示使用我们自定义的线程池。

package com.boot.test1.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class TranTest2Service {
    
    
    Logger log = LoggerFactory.getLogger(TranTest2Service.class);

    // 发送提醒短信 1
        @PostConstruct // 加上该注解项目启动时就执行一次该方法,在执行完构造方法实例化bean之后执行
    @Async("taskExecutor")
    public void sendMessage1() throws InterruptedException {
    
    
        log.info("发送短信方法---- 1   执行开始");
        Thread.sleep(5000); // 模拟耗时
        log.info("发送短信方法---- 1   执行结束");
    }

    // 发送提醒短信 2
        @PostConstruct // 加上该注解项目启动时就执行一次该方法,在执行完构造方法实例化bean之后执行
    @Async("taskExecutor")
    public void sendMessage2() throws InterruptedException {
    
    

        log.info("发送短信方法---- 2   执行开始");
        Thread.sleep(2000); // 模拟耗时
        log.info("发送短信方法---- 2   执行结束");
    }
}

第二个类
调用发短信的方法 (异步方法不能与被调用的异步方法在同一个类中,否则无效):

@Service
public class OrderTaskServic {
    
    
    @Autowired
    private TranTest2Service tranTest2Service;

    // 订单处理任务
    public void orderTask() throws InterruptedException {
    
    

        this.cancelOrder(); // 取消订单
        tranTest2Service.sendMessage1(); // 发短信的方法   1
        tranTest2Service.sendMessage2(); // 发短信的方法  2

    }

    // 取消订单
    public void cancelOrder() throws InterruptedException {
    
    
        System.out.println("取消订单的方法执行------开始");
        System.out.println("取消订单的方法执行------结束 ");
    }

}

运行截图:
在这里插入图片描述
注意看,截图中的 [nio-8090-exec-1] 是Tomcat的线程名称

[Async-Service-1]、[Async-Service-2]表示线程1和线程2 ,是我们自定义的线程池里面的线程名称,我们在配置类里面定义的线程池前缀:

private static final String threadNamePrefix = "Async-Service-";// 线程池名前缀,说明我们自定义的线程池被使用了。

注意事项
如下方式会使@Async失效
1-异步方法使用static修饰
2-异步类没有使用@Component注解(或其他注解)导致spring无法扫描到异步类
3-异步方法不能被同一个类中的另一个方法调用,因为spring 的这些注解是使用spring aop来动态代理的,同类调用时,我们是使用当前对象this来调用方法,而不是代理对象,因此aop无法生效。
4-类中需要使用@Autowired或@Resource等注解自动注入,不能自己手动new对象
5-如果使用SpringBoot框架必须在启动类中增加@EnableAsync注解

借鉴了大佬的博文
https://blog.csdn.net/Muscleheng/article/details/81409672

猜你喜欢

转载自blog.csdn.net/weixin_43944305/article/details/111659376