Spring-boot 中@Async使用的坑

一、首先使用@Async 須要在Spring啓動類上添加註解@EnableAsyn或者在大家線程池配置類添加@EnableAsynasync

一下兩種選擇一種便可spa

@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")代理

二、在使用@Async的時候切記不要在一個類裏面調用@Async聲明的方法,會產生代理繞過問題。code

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

    }

 

三、注意寫法blog

@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.";
    }                              
相關文章
相關標籤/搜索