spring boot 集成多线程

时间:2021-12-06 01:46:40

配置pom文件

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

线程池的配置文件

新建配置文件application.yml
添加内容

#线程池配置
spring:
task:
pool:
corePoolSize : 4
maxPoolSize : 8
keepAliveSeconds : 60
queueCapacity : 20

新建线程池参数装载类

@ConfigurationProperties(prefix = "spring.task.pool")
public class TaskThreadPoolConfig {
private int corePoolSize;

private int maxPoolSize;

private int keepAliveSeconds;

private int queueCapacity;

public int getCorePoolSize() {
return corePoolSize;
}

public void setCorePoolSize(int corePoolSize) {
this.corePoolSize = corePoolSize;
}

public int getMaxPoolSize() {
return maxPoolSize;
}

public void setMaxPoolSize(int maxPoolSize) {
this.maxPoolSize = maxPoolSize;
}

public int getKeepAliveSeconds() {
return keepAliveSeconds;
}

public void setKeepAliveSeconds(int keepAliveSeconds) {
this.keepAliveSeconds = keepAliveSeconds;
}

public int getQueueCapacity() {
return queueCapacity;
}

public void setQueueCapacity(int queueCapacity) {
this.queueCapacity = queueCapacity;
}
}

@ConfigurationProperties(prefix = “spring.task.pool”)是让spring在创建bean时去加载配置文件中开头为spring.task.pool的内容。

这一步需要在spring boot 启动类上加上注解:
@EnableConfigurationProperties({TaskThreadPoolConfig.class})
告诉spring 去根据配置文件的内容去创建bean

线程池的创建

@Configuration
@EnableAsync
public class TaskExecutePool {
@Autowired
private TaskThreadPoolConfig config;

@Bean
public Executor myTaskAsyncPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(config.getCorePoolSize());
executor.setMaxPoolSize(config.getMaxPoolSize());
executor.setQueueCapacity(config.getQueueCapacity());
executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
executor.setThreadNamePrefix("MyExecutor-");

// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}

创建多线程任务类和方法

@Component
public class doSomeThing{
@Async("myTaskAsyncPool")
public void produceTask(){
System.out.println("任务生产...");
}
@Async("myTaskAsyncPool")
public void comsumerTask(){
System.out.println("任务消费...");
}
}

注意:在需要多线程执行的类上加上注解@Component,在需要多线程执行的方法上加上@Async(“myTaskAsyncPool”)
spring boot 的多线程任务就搭好了,核心线程数量可以根据机器处理器核数进行确定。最好不要超过处理器核数。