spring-boot - Spring 启动 : Async method not running in separate Thread

标签 spring-boot asynchronous

我想在单独的线程中运行一个方法。因此我尝试使用 @Async 但它不起作用。打印输出始终引用相同的线程 id。

MyApp.java

@SpringBootApplication
@EnableAsync
@EnableConfigurationProperties(ConfigProperties.class)
public class MyApp {

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

    @Bean("threadPoolTaskExecutor")
    public TaskExecutor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(20);
        executor.setMaxPoolSize(1000);
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setThreadNamePrefix("Async-");
        return executor;
    }

}

MyService.java

@Slf4j
@Service
public class MyService implements ISichtServiceBroker {

@Inject
public MyService(Helper helper) {
    this.helper = helper;
}

@Transactional
public void handle(Message message) {
    System.out.println("Execute method synchronously - " + Thread.currentThread().getName());
    handleAsync(message);
}

@Async("threadPoolTaskExecutor")
public void handleAsync(Message message) {
    System.out.println("Execute method asynchronously - " + Thread.currentThread().getName());
}
}

最佳答案

  • Spring通过创建代理实现@Transactional@Async的预期效果。因此,当您注入(inject) MyService 时,实际上是在注入(inject) MyService 的代理,它包装了您的原始类实例。因此,如果调用通过此代理,那么这些注释将起作用,如果在没有代理的情况下直接调用该方法,它将不起作用。

  • 在你的情况下,当你想要 ProxyMyService .handle() --> MyService.handle() --> ProxyMyService。 handleAsync() -->MyService.handleAsync()

  • 为了实现这一点,您应该创建两个服务类并将一个方法放在类中,将第二个方法放在另一个中

注意

当您在两个不同的服务中执行此操作时,即使 handleAsync 将以事务方式执行,它也不会使用 handleAsync 方法中的事务。因为事务要在该方法内部传播,所以它们应该在同一个线程上执行

关于spring-boot - Spring 启动 : Async method not running in separate Thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63186811/

相关文章:

java - SpringBoot 将 RestTemplateBuilder 从 1.5.14 升级到 2.1.5

javascript - 从回调中获取空 promise

c# - 处理异步函数的空响应的正确方法是什么?

asynchronous - 'Async<string []>' 类型与 'seq<' 类型不兼容 a>'

c# - 超时使用 TaskCompletionSource 实现的异步方法

java - 将gzip添加到spring嵌入式tomcat中

intellij-idea - IntelliJ 运行与运行 jar,使用 Springboot Kotlin,使用 Social Oauth2 的多模块 Gradle 项目

javascript - 通过 Javascript 中的 promise 链传递状态有哪些模式?

java - Controller 类中无法识别 jsp 文件

Spring Boot - 类路径 list 属性