java – 升级到Spring Boot 1.3.3后@Async无法正常工作

前端之家收集整理的这篇文章主要介绍了java – 升级到Spring Boot 1.3.3后@Async无法正常工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一个在Spring Boot 1.2.3下运行的应用程序,它使用@Async注释的方法.到目前为止,它一直在正常工作.

升级到Spring Boot 1.3.3后,标记为@Async的方法不会在单独的线程中调用.

这是一个说明问题的示例程序:

App.java:

package test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;


@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = { "test" })
@EnableAsync
public class App implements CommandLineRunner {

    private static final Logger log = LoggerFactory.getLogger(App.class);

    @Autowired
    AsyncClass async;

    public static void main(String[] args) {
        SpringApplication.run(App.class,args);
    }

    public void run(String... arg0) throws Exception {
        log.info("in run");
        async.start();
        log.info("done run");
    }

}

AsyncClass.java:

package test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;


@Component
public class AsyncClass {

    private static final Logger log = LoggerFactory.getLogger(AsyncClass.class);

    @Async("myTaskExecutor")
    public void start() {
        log.info("in async task");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) { }
        log.info("done async task");
    }

    @Bean
    public ThreadPoolTaskExecutor myTaskExecutor() {

        ThreadPoolTaskExecutor bean = new ThreadPoolTaskExecutor();
        bean.setCorePoolSize(1);
        bean.setMaxPoolSize(1);
        bean.setQueueCapacity(10);
        bean.setThreadPriority(1);
        bean.setWaitForTasksToCompleteOnShutdown(true);
        return bean;
    }

}

pom.xml中:

在1.2.3下,start方法中的日志语句将它们显示为在线程myTaskExecutor-1中运行.在1.3.3下,相同的日志显示它们在主线程中运行.

知道这里可能有什么问题吗?

最佳答案
您需要将bean工厂方法放在另一个注释为@Configuration的类中. Executor将以这种方式用于@Async方法执行.

@Configuration
@EnableAsync
public class AsyncConfig {
   @Bean(name = "myTaskExecutor")
   public ThreadPoolTaskExecutor myTaskExecutor() {
      return new ThreadPoolTaskExecutor();
   }
}
原文链接:https://www.f2er.com/spring/432484.html

猜你在找的Spring相关文章