Spring Boot - 设置 TaskExecutor 的任何快捷方式? [英] Spring Boot - Any shortcuts for setting TaskExecutor?
问题描述
只是想签入看看是否有人有更快的方法在 spring 启动中为 Spring MVC 设置 TaskExecutor(使用自动配置).这是我目前所拥有的:
Just wanted to check in to see if anyone had a faster way to set the TaskExecutor for Spring MVC within spring boot (using auto configuration). This is what I have so far:
@Bean
protected ThreadPoolTaskExecutor mvcTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setThreadNamePrefix("my-mvc-task-executor-");
executor.setCorePoolSize(5);
executor.setMaxPoolSize(200);
return executor;
}
@Bean
protected WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
configurer.setTaskExecutor(mvcTaskExecutor());
}
};
}
有没有人有更好/更快的方法来做到这一点?
Does anyone have a better/faster way to do this?
-约书亚
推荐答案
实现此目的的一种方法是使用 Spring 的 ConcurrentTaskExceptor 类.该类充当 Spring 的 TaskExecutor 和 JDK 的 Executor 之间的适配器.
One way to achieve this is to use Spring's ConcurrentTaskExceptor class. This class acts as adapter between Spring's TaskExecutor and JDK's Executor.
@Bean
protected WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
configurer.setTaskExecutor(new ConcurrentTaskExecutor(Executors.newFixedThreadPool(5)));
}
};
}
上面的一个问题是您无法指定最大池大小.但是你总是可以创建一个新的工厂方法,createThreadPool(int core, int max)
来获得可配置的线程池.
One problem with above is that you can't specify maximum pool size. But you can always create a new factory method, createThreadPool(int core, int max)
to get you configurable thread pools.
这篇关于Spring Boot - 设置 TaskExecutor 的任何快捷方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!