搜索
您的当前位置:首页Spring-boot中@Async使用的坑

Spring-boot中@Async使用的坑

来源:爱问旅游网
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 + \ }

因篇幅问题不能全部显示,请点此查看更多更全内容

Top