Spring Boot @Async被称为Synchronously

时间:2015-10-23 09:22:20

标签: spring asynchronous spring-boot

我有一个长期运行的服务方法,我从控制器的休息呼叫开始。

服务:

@Service
public class TestServiceImpl implements TestService {

    @Override
    public void doSomething() {
        System.out.println("1: " + DateTime.now());
        runLongTask();
        System.out.println("2: " + DateTime.now());

    }

    @Async
    private runLongTask() {
        System.out.println("Test");
        Thread.sleep(10000);
        System.out.println("3: "+ DateTime.now());
    }
}

在我的Application.java中我有

private int poolSize = 10;

private int queueCapacity = 10;

@Bean(name="taskExecutor")
public TaskExecutor taskExecutor() {
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    taskExecutor.setMaxPoolSize(this.poolSize);
    taskExecutor.setQueueCapacity(this.queueCapacity);
    taskExecutor.afterPropertiesSet();
    return new ThreadPoolTaskExecutor();
}

当然,我的Application.java类中有@EnableAsync Annotation

所以我希望输出是这样的:

1: 2015-10-23 11:20:00
2: 2015-10-23 11:20:01
Test
3: 2015-10-23 11:20:11

2 个答案:

答案 0 :(得分:7)

您需要从不同的类调用方法来使用@Async@Transactional等注释。 Spring通过代理包装带注释的方法来完成这些工作。如果你从同一个类调用方法,那么它就没有效果了。

答案 1 :(得分:1)

根据documentation,您需要在Configuration类中实现Application接口(在本例中我假设是您的SimpleAsyncTaskExecutor实例)来覆盖{{ 1}}。

文档中还显示了一个完整的示例:

 @Configuration
 @EnableAsync
 public class AppConfig implements AsyncConfigurer {

 @Bean
 public MyAsyncBean asyncBean() {
     return new MyAsyncBean();
 }

 @Override
 public Executor getAsyncExecutor() {
     ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
     executor.setCorePoolSize(7);
     executor.setMaxPoolSize(42);
     executor.setQueueCapacity(11);
     executor.setThreadNamePrefix("MyExecutor-");
     executor.initialize();
     return executor;
 }

 @Override
 public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
         return MyAsyncUncaughtExceptionHandler();
 }
}

HTH,

何塞路易斯