spring boot 异步任务
程序员文章站
2022-05-01 14:18:36
...
package com.boot.mytt.core.tasks;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.task.TaskExecutorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
public class TaskConfig {
@Bean
public ThreadPoolTaskExecutor customTaskExecutor(TaskExecutorBuilder taskExecutorBuilder) {
return taskExecutorBuilder.threadNamePrefix("customTask-")
.corePoolSize(5).build();
}
@Bean
public ThreadPoolTaskExecutor myTaskExecutor(TaskExecutorBuilder taskExecutorBuilder) {
return taskExecutorBuilder.threadNamePrefix("myTask-")
.corePoolSize(10).build();
}
@Bean
CommandLineRunner clrTask(AsyncTask asyncTask) {
return args -> {
for (int k=0; k<10; k++) {
asyncTask.loopPrint(k);
}
for (int k=0; k<10; k++) {
asyncTask.loopPrint2(k);
}
};
}
}
package com.boot.mytt.core.tasks;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class AsyncTask {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Async("customTaskExecutor")
public void loopPrint(Integer k) {
log.info(Thread.currentThread().getName() + ":" + k);
}
@Async("myTaskExecutor")
public void loopPrint2(Integer k) {
log.info(Thread.currentThread().getName() + ":" + k);
}
}
或属性配置:
book:
name: zhangsan
age: 22
spring:
main:
allow-bean-definition-overriding: true
task:
execution:
pool:
core-size: 10
max-size: 20
thread-name-prefix: mytask-
logging:
level:
org:
springframework:
web: DEBUG
file:
path: d:/logs
上一篇: 使用Executors创建线程池的思考
下一篇: 不:第一个孩子选择器
推荐阅读
-
java-使用war将spring-boot和angular 7应用程序部署到tomcat 8.5中
-
(转)Spring boot 切换配置文件到yaml
-
将Spring Boot JAR应用程序转换为WAR
-
将Spring Boot应用程序绑定到Cloud Foundry中的服务的方法
-
Spring Boot应用程序创建可部署的war文件到tomcat
-
将Spring Boot应用程序注册成为系统服务
-
将Spring Boot程序打包成docker镜像-超简版
-
spring Boot环境下dubbo+zookeeper的一个基础讲解与示例
-
Spring Boot使用redis做数据缓存
-
Spring Boot 实战 入门