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.";
    }                              
相关文章
相关标签/搜索