ThreadPoolExecutor的corePoolSize和maximumPoolSize的set方法都是public的,可以进行设置值,队列大小的参数是final,修改不了,但是可以通过改造也可以动态修改队列大小
spring的ThreadPoolTaskExecutor是对Jdk的ThreadPoolExecutor的进一步封装,使用的是装饰器模式
使用dynamic-tp动态线程池 官网地址
使用springcloud演示,把线程池参数配置放进nacos进行配置
1.引入依赖
<dependency>
<groupId>cn.dynamictp</groupId>
<artifactId>dynamic-tp-spring-boot-starter-extension-notify-email</artifactId>
</dependency>
2.启动类上注解@EnableDynamicTp
3.nacos配置文件中添加配置
spring:
# email notify configuration
mail:
# (optional) email subject, default:ThreadPool Notify
title: ThreadPool Notify
# mail service address
host: smtp.163.com
port: 465
# send from
username: st1913996xx56@163.com
# authorization code eg: rlpadadtcugh4152e
password: QXXIGHJDYOSGxxxx
default-encoding: UTF-8
properties:
mail:
smtp:
socketFactoryClass: javax.net.ssl.SSLSocketFactory
ssl:
enable: true
debug: false
dynamic:
tp:
enabled: true
enabledBanner: true # 是否开启banner打印,默认true
enabledCollect: true # 是否开启监控指标采集,默认false
collectorTypes: micrometer,logging # 监控数据采集器类型(logging | micrometer | internal_logging),默认micrometer
logPath: /home/logs # 监控日志数据路径,默认 ${user.home}/logs,采集类型非logging不用配置
monitorInterval: 5 # 监控时间间隔(报警判断、指标采集),默认5s
platforms: # 通知报警平台配置
- platform: email
receivers: 15136161050@163.com
tomcatTp: # tomcat webserver线程池配置
corePoolSize: 100
maximumPoolSize: 200
keepAliveTime: 60
executors: # 动态线程池配置
- threadPoolName: dtpExecutor
threadPoolAliasName: 测试线程池 # 线程池别名
executorType: common # 线程池类型common、eager:适用于io密集型
corePoolSize: 5
maximumPoolSize: 18
queueCapacity: 400
queueType: VariableLinkedBlockingQueue # 任务队列,查看源码QueueTypeEnum枚举类
rejectedHandlerType: CallerRunsPolicy # 拒绝策略,查看RejectedTypeEnum枚举类
keepAliveTime: 50
allowCoreThreadTimeOut: false # 是否允许核心线程池超时
threadNamePrefix: test # 线程名前缀
waitForTasksToCompleteOnShutdown: false # 参考spring线程池设计,优雅关闭线程池
awaitTerminationSeconds: 5 # 单位(s)
preStartAllCoreThreads: false # 是否预热所有核心线程,默认false
runTimeout: 200 # 任务执行超时阈值,目前只做告警用,单位(ms)
queueTimeout: 100 # 任务在队列等待超时阈值,目前只做告警用,单位(ms)
taskWrapperNames: ["ttl"] # 任务包装器名称,集成TaskWrapper接口
notifyItems: # 报警项,不配置自动会按默认值配置(变更通知、容量报警、活性报警、拒绝报警、任务超时报警)
- type: capacity # 报警项类型,查看源码 NotifyTypeEnum枚举类
enabled: true
threshold: 80 # 报警阈值
platforms: [ding,wechat] # 可选配置,不配置默认拿上层platforms配置的所以平台
interval: 120 # 报警间隔(单位:s)
- type: change
enabled: true
- type: liveness
enabled: true
threshold: 80
- type: reject
enabled: true
threshold: 1
- type: run_timeout
enabled: true
threshold: 1
- type: queue_timeout
enabled: true
threshold: 1
4.测试
@GetMapping("testDynamicPool")
public void testDynamicPool() {
dtpExecutor.execute(()-> System.out.println("测试动态线程池"));
log.info("核心线程数:{},最大线程数:{},队列大小:{}",dtpExecutor.getCorePoolSize(),dtpExecutor.getMaximumPoolSize(),dtpExecutor.getQueueCapacity());
}
在nacos中修改之后访问接口会看到修改的结果