Spring 异步任务与定时任务的线程配置

异步任务和定时任务的默认线程配置

IDEA文件目录树 -> External Libraries -> 找到 spring-boot-autoconfigure-*.jar -> 找到TaskExecutionProperties文件
可以得知 异步任务的 默认配置为:
private int queueCapacity = Integer.MAX_VALUE;
private int coreSize = 8; (默认8个线程)
private int maxSize = Integer.MAX_VALUE; (线程最大值)
private Duration keepAlive = Duration.ofSeconds(60);

jar启动的时候,不会直接分配8个线程. 只有请求上来了才会初始化线程.

在这里插入图片描述
找到 TaskSchedulingProperties 文件,可以得知定时任务的默认配置为
private int size = 1; (单线程)

调整异步任务的线程配置

配置文件修改

spring.task.execution.pool.max-size=16
spring.task.execution.pool.queue-capacity=100
spring.task.execution.pool.keep-alive=10s

或者编程式的方式修改

@Configuration
@EnableAsync
public class AppConfig implements AsyncConfigurer {

   @Override
   public Executor getAsyncExecutor() {
       ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
       executor.setCorePoolSize(7);
       executor.setMaxPoolSize(42);
       executor.setQueueCapacity(11);
       executor.setThreadNamePrefix("MyExecutor-");
       executor.initialize();
       return executor;
   }

   @Override
   public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
       return new MyAsyncUncaughtExceptionHandler();
   }
}

调整定时任务的线程配置

application.yml配置文件添加配置节点
spring.task.scheduling.pool.size

使用Java VisualVM查看线程

jar启动添加jvm参数

-Dcom.sun.management.jmxremote.port=8999 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Djava.rmi.server.hostname=localhost

打开VisualVM 设置连接 localhsot:8999
在这里插入图片描述


版权声明:本文为weixin_46903045原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。