Pav*_*vlo 20 java concurrency spring asynchronous
我@Service
在Spring Boot应用程序中创建了一个类,其中一个方法应该异步运行.因为我读取方法应该@Async
注释,我也必须运行一个TaskExecutor
bean.但是在Spring手册http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html我没有找到任何信息或示例如何TaskExecutor
使用注释运行,没有XML配置.是否可以TaskExecutor
在没有XML的情况下在Spring Boot中创建bean,仅注释?这是我的服务类:
@Service
public class CatalogPageServiceImpl implements CatalogPageService {
@Override
public void processPagesList(List<CatalogPage> catalogPageList) {
for (CatalogPage catalogPage:catalogPageList){
processPage(catalogPage);
}
}
@Override
@Async("locationPageExecutor")
public void processPage(CatalogPage catalogPage) {
System.out.println("print from Async method "+catalogPage.getUrl());
}
}
Run Code Online (Sandbox Code Playgroud)
Jes*_*per 36
@Bean
在Spring Boot应用程序类中添加一个方法:
@SpringBootApplication
@EnableAsync
public class MySpringBootApp {
@Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
return executor;
}
public static void main(String[] args) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅Spring Framework参考文档中有关如何使用Java配置而不是XML配置Spring 的基于Java的容器配置.
(注意:您不需要添加@Configuration
到类中,因为@SpringBootApplication
已经包含@Configuration
).
Der*_*lin 15
更新:从Spring Boot 2.1开始,无需创建ThreadPoolTaskExecutor
直通代码,因为它ThreadPoolTaskExecutor
是默认值,并且可以使用前缀为 的属性来完全配置spring.task.execution
。
那么,步骤:
@EnableAsync
在带注释的类中使用@Configuration
,@Async
ThreadPoolTaskExecutor
可以选择使用属性覆盖默认配置属性示例:
spring.task.execution.pool.core-size=1
spring.task.execution.pool.max-size=20
spring.task.execution.pool.keep-alive=120s
spring.task.execution.pool.queue-capacity=1000
spring.task.execution.shutdown.await-termination=true
spring.task.execution.shutdown.await-termination-period=5m
spring.task.execution.thread-name-prefix=async-executor-
spring.task.execution.pool.allow-core-thread-timeout=false
Run Code Online (Sandbox Code Playgroud)
如果需要更多定制,还可以实现该TaskExecutorCustomizer
接口,例如(在 kotlin 中):
spring.task.execution.pool.core-size=1
spring.task.execution.pool.max-size=20
spring.task.execution.pool.keep-alive=120s
spring.task.execution.pool.queue-capacity=1000
spring.task.execution.shutdown.await-termination=true
spring.task.execution.shutdown.await-termination-period=5m
spring.task.execution.thread-name-prefix=async-executor-
spring.task.execution.pool.allow-core-thread-timeout=false
Run Code Online (Sandbox Code Playgroud)
小智 6
首先 - 让我们回顾一下规则 - @Async有两个限制:
所以你的processPage()方法应该在单独的类中
归档时间: |
|
查看次数: |
38512 次 |
最近记录: |