Spring Boot 多线程
Wenhao Wang 2020-07-23 多线程Spring Boot
Spring Boot 配置线程池和多线程的使用
# Sring Boot中使用多线程
// 第一步-配置线程池
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author wwh
* @date 2019/11/7 10:29
* @description
*/
@EnableAsync
@Configuration
public class ThreadPoolConfig {
@Bean("testTaskExecutor") // 可以以指定Bean名称的方式注入多个线程池
public TaskExecutor getTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心线程数
executor.setCorePoolSize(12);
// 最大线程数
executor.setMaxPoolSize(20);
// 队列大小
executor.setQueueCapacity(Integer.MAX_VALUE);
// 线程活跃时间
executor.setKeepAliveSeconds(60);
// 默认线程名称
executor.setThreadNamePrefix("1874-");
// 拒绝策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 等待所有任务结束关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
return executor;
}
}
// 第二步-在启动类或者配置类添加注解@EnableAsync来开启异步调用
// 第三步-在要被异步值执行的方法上添加@Async注解,可以指定要使用的线程池,如@Async("testTaskExecutor"),该注解加在类上表示类中所有方法都是异步方法,加在方法上表示该方法是异步方法
注意事项:
当并发量过大时,即超出了线程池队列设置的大小,主线程会新建线程池外的线程用于处理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# Spring Boot中配置多环境配置文件
1.在applications.properties中指定要启用的配置文件
spring.profiles.active={profile}
2.按照Spring Boot规则建立不同环境的配置文件
规则:applications-{profile}.properties
在启动的时候只需要修改主配置文件即applications.properties中的spring.profiles.active={profile}就可以激活不同的环境
1
2
3
4
5
6
2
3
4
5
6