Spring-boot 中@Async使用的坑

1、首先使用@Async 需要在Spring启动类上添加注解@EnableAsyn或者在你们线程池配置类添加@EnableAsyn

一下两种选择一种即可

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

    @Bean("simpleThreadPool")
    public ThreadPoolTaskExecutor simpleThreadPool(){
        ThreadPoolTaskExecutor simpleThreadPool = new ThreadPoolTaskExecutor();
        simpleThreadPool.setCorePoolSize(5);
        simpleThreadPool.setMaxPoolSize(10);
        simpleThreadPool.setQueueCapacity(25);
        simpleThreadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        simpleThreadPool.initialize();
        return simpleThreadPool;
    }
}

注意如果自己配置了线程池那么在使用的时候需要保持一致

例如:@Async("simpleThreadPool")

2、在使用@Async的时候切记不要在一个类里面调用@Async声明的方法,会产生代理绕过问题。

   @Async
    public void asyncProcess() throws InterruptedException {
       
        Thread.sleep(2000);

    }

3、注意写法

@Autowired
private AsyncTaskService asyncTaskService;

public String asyncMethod(String name,int age) {
        OnelogStats.trace("msg_async", "进入service");
        try {
             // 初学者可能会有这种错误,AsyncTaskService没有注入到Spring导致Async不起作用,注释不规范
            //new AsyncTaskService().asyncProcess();
            asyncTaskService.asyncProcess();
        } catch (InterruptedException e) {
            return "async error";
        }
        return "I am " + name + ", I am " + age + " years old.";
    }                              
原文地址:https://www.cnblogs.com/wangchaoyu/p/10461386.html