gpt4 book ai didi

@Async 方法中的 Spring @Async 方法

转载 作者:行者123 更新时间:2023-12-03 12:54:12 27 4
gpt4 key购买 nike

您好,我正在试用 Springs 异步执行器,发现您可以使用 @Async。我想知道是否有可能在 @Async 中使用 @Async,要求是需要将任务委托(delegate)给 @Async 方法在第一个 @Async 方法中调用。

例如:目录中有 100 个文件,需要创建作业在 5 个线程中处理 20 个文件。

最佳答案

如果两个异步方法定义在两个不同的类中,那么您将能够从第一个异步方法调用第二个异步方法。但是,如果它们都在同一个类中,则第二个方法的执行将在处理第一个方法本身的线程中内联。查看this回答更多细节和一些相同的解决方法。

对于您的具体情况,您可以定义两个线程池执行器,一个用于第一个异步方法,另一个用于第二个异步方法。 @Async 注释有一个 value 参数,您可以将应该使用的线程池执行程序传递给该参数。

下面是一个使用两个执行器的例子。

@SpringBootApplication
@EnableAspectJAutoProxy
@EnableAsync
public class MultipleExecutorsExample {

@Bean
public ThreadPoolTaskExecutor executor1() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setCorePoolSize(10);
threadPoolTaskExecutor.setMaxPoolSize(10);
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}

@Bean
public ThreadPoolTaskExecutor executor2() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setCorePoolSize(5);
threadPoolTaskExecutor.setMaxPoolSize(5);
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}

public static void main(String[] args) throws BeansException, InterruptedException {
ConfigurableApplicationContext context = new SpringApplicationBuilder(MultipleExecutorsExample.class)
.web(WebApplicationType.NONE).build().run(args);
context.getBean(Service1.class).execute();
}

}

带有第一个异步方法的Service1

@Component
@Slf4j
public class Service1 {

@Autowired
private Service2 service2;

@Async("executor1")
public void execute() throws InterruptedException {
log.info("Sleeping for 5 seconds");
for (int i = 1; i <= 10; i++) {
service2.execute();
}
}

}

带有第二个异步方法的Service2

@Component
@Slf4j
public class Service2 {

@Async("executor2")
public void execute() throws InterruptedException {
log.info("Sleeping for 1 seconds");
Thread.sleep(1000);
}

}

程序的输出显示两个异步任务正在使用不同的执行程序。

018-05-30 18:44:27.557  INFO 19839 --- [  restartedMain] c.e.demo.tp.MultipleExecutorsExample     : Started MultipleExecutorsExample in 1.926 seconds (JVM running for 2.407)
2018-05-30 18:44:27.567 INFO 19839 --- [ executor1-1] com.example.demo.tp.Service1 : Sleeping for 5 seconds
2018-05-30 18:44:27.570 INFO 19839 --- [ executor2-1] com.example.demo.tp.Service2 : Sleeping for 1 seconds
2018-05-30 18:44:27.570 INFO 19839 --- [ executor2-2] com.example.demo.tp.Service2 : Sleeping for 1 seconds
2018-05-30 18:44:27.570 INFO 19839 --- [ executor2-5] com.example.demo.tp.Service2 : Sleeping for 1 seconds

关于@Async 方法中的 Spring @Async 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50603050/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com