0


科普文:微服务之SpringBoot性能优化器动态线程池【Dynamic-Tp】特性和源码解读

一、简述

gitee地址https://gitee.com/yanhom/dynamic-tp

github地址https://github.com/lyh200/dynamic-tp

  1. dynamic-tp

是一个轻量级的动态线程池插件,它是一个基于配置中心的动态线程池,线程池的参数可以通过配置中心配置进行动态的修改,目前支持的配置中心有

  1. Apollo

  1. Nacos

  1. Zookeeper

,同时

  1. dynamic-tp

支持线程池的监控和报警,具体特性如下:

  • 基于Spring框架,现只支持SpringBoot项目使用,轻量级,引入starter即可使用
  • 基于配置中心实现线程池参数动态调整,实时生效;集成主流配置中心,已支持NacosApolloZookeeper,同时也提供SPI接口可自定义扩展实现
  • 内置通知报警功能,提供多种报警维度(配置变更通知、活性报警、容量阈值报警、拒绝策略触发报警),默认支持企业微信、钉钉报警,同时提供SPI接口可自定义扩展实现
  • 内置线程池指标采集功能,支持通过MicroMeterJsonLog日志输出、Endpoint三种方式,可通过SPI接口自定义扩展实现
  • 集成管理常用第三方组件的线程池,已集成SpringBoot内置WebServer(tomcatundertowjetty)的线程池管理
  • Builder提供TTL包装功能,生成的线程池支持上下文信息传递

代码结构

代码结构

代码结构

1.adapter模块:主要是适配一些第三方组件的线程池管理,目前已经实现的有SpringBoot内置的三大web容器(Tomcat、Jetty、Undertow)的线程池管理,后续可能接入其他常用组件的线程池管理。

2.common模块:主要是一些各个模板都会用到的类,解耦依赖,复用代码,大家日常开发中可能也经常会这样做。

3.core模块:该框架的核心代码都在这个模块里,包括动态调整参数,监控报警,以及串联整个项目流程都在此。

4.example模块:提供一个简单使用示例,方便使用者参照

5.logging模块:用于配置框架内部日志的输出,目前主要用于输出线程池监控指标数据到指定文件

6.starter模块:集成各个配置中心实现动态更新配置,目前已经集成Nacos、Apollo两个主流配置中心,使用者也可以参照扩展其他配置中心实现,客户端使用也只需引入相应starter依赖就行。

二、源码分析

在分析源码之前,我们先来思考下如果是我们来实现动态线程池组件应该如何设计。

  1. 首先不论是硬编码的线程池还是通过配置化动态生成的线程池都是一类线程池(同一基类),而这一类线程池的参数可以抽象成配置,这个配置既可以是本项目中的文件;也可以是任意远程端口的文件,例如包括业界的配置中心们例如nacoszookeeperapolloetcd等;当然它甚至可以不依赖配置中心,通过前端管理系统页面配置,走DB,通过刷新API接口中的String类型的文本配置,进而刷新线程池配置,这也是一种实现思路。
  2. 提供一个功能入口可以将配置构造成一个线程池对象,内部维护一个线程池注册表,将配置对应的线程池添加至注册表中。
  3. 实例化线程池对象,Spring环境则注入依赖Bean,以供IOC容器使用。
  4. 项目启动时首先先加载配置实例化线程池对象
  5. 如果配置指向的是远端配置中心,则注册监听器,当远端注册配置中心刷新时回调,当前系统监听到回调刷新配置,刷新线程池(动态调参),刷新本地线程池注册表。

至此我们设计出来的简易动态线程池组件应该可以基本使用了。

其实简易动态线程池组件还有很多进步的空间,例如线程池调参监控,异常报警等。

当然以上说的这些基础功能以及额外的高级功能,

  1. dynamic-tp

都已经实现了,不过它目前没有提供支持我们刚刚所说通过管理系统页面配置走

  1. DB

通过接口刷新的官方实现,且不支持除配置中心应用外的选择,也就是说无配置中心应用,目前不支持线程池动态调参(但支持监控),但事实上你可以根据它提供的

  1. SPI

自行实现。
这可能

  1. dynamic-tp

定位是轻量级动态线程池组件,且配置中心是现在大多数互联网系统都会使用的组件有关。

2.1 配置

  1. dynamic-tp

通过

  1. DtpProperties

来做配置的统一收口,这个配置包括本地文件或者配置中心中的文件

  1. (properties

  1. json

  1. yml

  1. txt

  1. xml)

,可以看到目前已支持

  1. Nacos

  1. Apollo

  1. Zookeeper

  1. Consul

  1. Etcd

配置中心

  1. @Slf4j
  2. @Data
  3. @ConfigurationProperties(prefix = DynamicTpConst.MAIN_PROPERTIES_PREFIX)
  4. public class DtpProperties {
  5. /**
  6. * If enabled DynamicTp.
  7. */
  8. private boolean enabled = true;
  9. /**
  10. * If print banner.
  11. */
  12. private boolean enabledBanner = true;
  13. /**
  14. * Nacos config.
  15. */
  16. private Nacos nacos;
  17. /**
  18. * Apollo config.
  19. */
  20. private Apollo apollo;
  21. /**
  22. * Zookeeper config.
  23. */
  24. private Zookeeper zookeeper;
  25. /**
  26. * Etcd config.
  27. */
  28. private Etcd etcd;
  29. /**
  30. * Config file type.
  31. */
  32. private String configType = "yml";
  33. /**
  34. * If enabled metrics collect.
  35. */
  36. private boolean enabledCollect = false;
  37. /**
  38. * Metrics collector types, default is logging.
  39. */
  40. private List<String> collectorTypes = Lists.newArrayList(MICROMETER.name());
  41. /**
  42. * Metrics log storage path, just for "logging" type.
  43. */
  44. private String logPath;
  45. /**
  46. * Monitor interval, time unit(s)
  47. */
  48. private int monitorInterval = 5;
  49. /**
  50. * ThreadPoolExecutor configs.
  51. */
  52. private List<ThreadPoolProperties> executors;
  53. /**
  54. * Tomcat worker thread pool.
  55. */
  56. private SimpleTpProperties tomcatTp;
  57. /**
  58. * Jetty thread pool.
  59. */
  60. private SimpleTpProperties jettyTp;
  61. /**
  62. * Undertow thread pool.
  63. */
  64. private SimpleTpProperties undertowTp;
  65. /**
  66. * Dubbo thread pools.
  67. */
  68. private List<SimpleTpProperties> dubboTp;
  69. /**
  70. * Hystrix thread pools.
  71. */
  72. private List<SimpleTpProperties> hystrixTp;
  73. /**
  74. * RocketMq thread pools.
  75. */
  76. private List<SimpleTpProperties> rocketMqTp;
  77. /**
  78. * Grpc thread pools.
  79. */
  80. private List<SimpleTpProperties> grpcTp;
  81. /**
  82. * Motan server thread pools.
  83. */
  84. private List<SimpleTpProperties> motanTp;
  85. /**
  86. * Okhttp3 thread pools.
  87. */
  88. private List<SimpleTpProperties> okhttp3Tp;
  89. /**
  90. * Brpc thread pools.
  91. */
  92. private List<SimpleTpProperties> brpcTp;
  93. /**
  94. * Tars thread pools.
  95. */
  96. private List<SimpleTpProperties> tarsTp;
  97. /**
  98. * Sofa thread pools.
  99. */
  100. private List<SimpleTpProperties> sofaTp;
  101. /**
  102. * Notify platform configs.
  103. */
  104. private List<NotifyPlatform> platforms;
  105. @Data
  106. public static class Nacos {
  107. private String dataId;
  108. private String group;
  109. private String namespace;
  110. }
  111. @Data
  112. public static class Apollo {
  113. private String namespace;
  114. }
  115. @Data
  116. public static class Zookeeper {
  117. private String zkConnectStr;
  118. private String configVersion;
  119. private String rootNode;
  120. private String node;
  121. private String configKey;
  122. }
  123. /**
  124. * Etcd config.
  125. */
  126. @Data
  127. public static class Etcd {
  128. private String endpoints;
  129. private String user;
  130. private String password;
  131. private String charset = "UTF-8";
  132. private Boolean authEnable = false;
  133. private String authority = "ssl";
  134. private String key;
  135. }
  136. }

项目中提供了一个配置解析接口

  1. ConfigParser
  1. public interface ConfigParser {
  2. // 是否支持配置解析
  3. boolean supports(ConfigFileTypeEnum type);
  4. // 解析支持的类型
  5. List<ConfigFileTypeEnum> types();
  6. // 解析
  7. Map<Object, Object> doParse(String content) throws IOException;
  8. // 解析指定前缀
  9. Map<Object, Object> doParse(String content, String prefix) throws IOException;
  10. }
  1. ConfigFileTypeEnum

如下,覆盖了主流文件类型

  1. @Getter
  2. public enum ConfigFileTypeEnum {
  3. PROPERTIES("properties"),
  4. XML("xml"),
  5. JSON("json"),
  6. YML("yml"),
  7. YAML("yaml"),
  8. TXT("txt");
  9. }

项目中实现了配置解析基类,以及默认提供了

  1. 3

中文件类型配置解析类,

  1. json

  1. properties

以及

  1. yaml

,使用者完全可以通过继承

  1. AbstractConfigParser

来补充配置解析模式。

  1. AbstractConfigParser

代码如下,模板方法由子类实现具体的解析逻辑。

  1. public abstract class AbstractConfigParser implements ConfigParser {
  2. @Override
  3. public boolean supports(ConfigFileTypeEnum type) {
  4. return this.types().contains(type);
  5. }
  6. @Override
  7. public Map<Object, Object> doParse(String content, String prefix) throws IOException {
  8. return doParse(content);
  9. }
  10. }

子类的实现这里就不看了,大差不差就是通过读取文件,解析每一行配置项,最后将结果封装成

  1. Map<Object, Object> result

返回。

接着通过

  1. Spring-bind

提供的解析方法将

  1. Map<Object, Object> result

绑定到

  1. DtpProperties

配置类上

实现代码如下:

  1. public class PropertiesBinder {
  2. private PropertiesBinder() { }
  3. public static void bindDtpProperties(Map<?, Object> properties, DtpProperties dtpProperties) {
  4. ConfigurationPropertySource sources = new MapConfigurationPropertySource(properties);
  5. Binder binder = new Binder(sources);
  6. ResolvableType type = ResolvableType.forClass(DtpProperties.class);
  7. Bindable<?> target = Bindable.of(type).withExistingValue(dtpProperties);
  8. binder.bind(MAIN_PROPERTIES_PREFIX, target);
  9. }
  10. public static void bindDtpProperties(Environment environment, DtpProperties dtpProperties) {
  11. Binder binder = Binder.get(environment);
  12. ResolvableType type = ResolvableType.forClass(DtpProperties.class);
  13. Bindable<?> target = Bindable.of(type).withExistingValue(dtpProperties);
  14. binder.bind(MAIN_PROPERTIES_PREFIX, target);
  15. }
  16. }

到这里已经拿到了配置,我们来看接下来的流程。

2.2 注册线程池

  1. DtpBeanDefinitionRegistrar

实现了

  1. ConfigurationClassPostProcessor

利用

  1. Spring

的动态注册

  1. bean

机制,在

  1. bean

初始化之前注册

  1. BeanDefinition

以达到注入

  1. bean

的目的

ps:最终被

  1. Spring ConfigurationClassPostProcessor

执行出来对这块不熟悉的小伙伴可以去翻看

  1. Spring

源码。

来看下DtpBeanDefinitionRegistrar具体做了什么吧

  1. @Slf4j
  2. public class DtpBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware {
  3. private Environment environment;
  4. @Override
  5. public void setEnvironment(Environment environment) {
  6. this.environment = environment;
  7. }
  8. @Override
  9. public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
  10. BeanDefinitionRegistry registry) {
  11. DtpProperties dtpProperties = new DtpProperties();
  12. // 从 Environment 读取配置信息绑定到 DtpProperties
  13. PropertiesBinder.bindDtpProperties(environment, dtpProperties);
  14. // 获取配置文件中配置的线程池
  15. val executors = dtpProperties.getExecutors();
  16. if (CollectionUtils.isEmpty(executors)) {
  17. log.warn("DynamicTp registrar, no executors are configured.");
  18. return;
  19. }
  20. // 遍历并注册线程池 BeanDefinition
  21. executors.forEach(x -> {
  22. // 类型选择,common->DtpExecutor,eager->EagerDtpExecutor
  23. Class<?> executorTypeClass = ExecutorType.getClass(x.getExecutorType());
  24. // 通过 ThreadPoolProperties 来构造线程池所需要的属性
  25. Map<String, Object> properties = buildPropertyValues(x);
  26. Object[] args = buildConstructorArgs(executorTypeClass, x);
  27. // 工具类 BeanDefinition 注册 Bean 相当于手动用 @Bean 声明线程池对象
  28. BeanUtil.registerIfAbsent(registry, x.getThreadPoolName(), executorTypeClass,
  29. properties, args);
  30. });
  31. }
  32. }
  1. registerBeanDefinitions

方法中主要做了这么几件事

  1. Environment读取配置信息绑定到DtpProperties
  2. 获取配置文件中配置的线程池,如果没有则结束
  3. 遍历线程池,绑定配置构造线程池所需要的属性,根据配置中的executorType注册不同类型的线程池Bean(下面会说)
  4. BeanUtil#registerIfAbsent()注册Bean
  1. ExecutorType

目前项目支持3种类型,分别对应3个线程池,这里先跳过,我们下文详细介绍

回到刚才的步骤,接下来通过

  1. ThreadPoolProperties

来构造线程池所需要的属性

  1. private Map<String, Object> buildPropertyValues(ThreadPoolProperties tpp) {
  2. Map<String, Object> properties = Maps.newHashMap();
  3. properties.put(THREAD_POOL_NAME, tpp.getThreadPoolName());
  4. properties.put(THREAD_POOL_ALIAS_NAME, tpp.getThreadPoolAliasName());
  5. properties.put(ALLOW_CORE_THREAD_TIMEOUT, tpp.isAllowCoreThreadTimeOut());
  6. properties.put(WAIT_FOR_TASKS_TO_COMPLETE_ON_SHUTDOWN, tpp.isWaitForTasksToCompleteOnShutdown());
  7. properties.put(AWAIT_TERMINATION_SECONDS, tpp.getAwaitTerminationSeconds());
  8. properties.put(PRE_START_ALL_CORE_THREADS, tpp.isPreStartAllCoreThreads());
  9. properties.put(RUN_TIMEOUT, tpp.getRunTimeout());
  10. properties.put(QUEUE_TIMEOUT, tpp.getQueueTimeout());
  11. val notifyItems = mergeAllNotifyItems(tpp.getNotifyItems());
  12. properties.put(NOTIFY_ITEMS, notifyItems);
  13. properties.put(NOTIFY_ENABLED, tpp.isNotifyEnabled());
  14. val taskWrappers = TaskWrappers.getInstance().getByNames(tpp.getTaskWrapperNames());
  15. properties.put(TASK_WRAPPERS, taskWrappers);
  16. return properties;
  17. }

选择阻塞队列,这里针对

  1. EagerDtpExecutor

做了单独处理,选择了

  1. TaskQueue

作为阻塞队列(下文说明)

  1. private Object[] buildConstructorArgs(Class<?> clazz, ThreadPoolProperties tpp) {
  2. BlockingQueue<Runnable> taskQueue;
  3. // 如果是 EagerDtpExecutor 的话,对工作队列就是 TaskQueue
  4. if (clazz.equals(EagerDtpExecutor.class)) {
  5. taskQueue = new TaskQueue(tpp.getQueueCapacity());
  6. } else {
  7. // 不是 EagerDtpExecutor的话,就根据配置中的 queueType 来选择阻塞的队列
  8. taskQueue = buildLbq(tpp.getQueueType(), tpp.getQueueCapacity(), tpp.isFair(),
  9. tpp.getMaxFreeMemory());
  10. }
  11. return new Object[]{
  12. tpp.getCorePoolSize(),
  13. tpp.getMaximumPoolSize(),
  14. tpp.getKeepAliveTime(),
  15. tpp.getUnit(),
  16. taskQueue,
  17. new NamedThreadFactory(tpp.getThreadNamePrefix()),
  18. RejectHandlerGetter.buildRejectedHandler(tpp.getRejectedHandlerType())
  19. };
  20. }

  1. EagerDtpExecutor

则根据配置中的

  1. queueType

来选择阻塞的队列

  1. public static BlockingQueue<Runnable> buildLbq(String name, int capacity, boolean fair,
  2. int maxFreeMemory) {
  3. BlockingQueue<Runnable> blockingQueue = null;
  4. if (Objects.equals(name, ARRAY_BLOCKING_QUEUE.getName())) {
  5. blockingQueue = new ArrayBlockingQueue<>(capacity);
  6. } else if (Objects.equals(name, LINKED_BLOCKING_QUEUE.getName())) {
  7. blockingQueue = new LinkedBlockingQueue<>(capacity);
  8. } else if (Objects.equals(name, PRIORITY_BLOCKING_QUEUE.getName())) {
  9. blockingQueue = new PriorityBlockingQueue<>(capacity);
  10. } else if (Objects.equals(name, DELAY_QUEUE.getName())) {
  11. blockingQueue = new DelayQueue();
  12. } else if (Objects.equals(name, SYNCHRONOUS_QUEUE.getName())) {
  13. blockingQueue = new SynchronousQueue<>(fair);
  14. } else if (Objects.equals(name, LINKED_TRANSFER_QUEUE.getName())) {
  15. blockingQueue = new LinkedTransferQueue<>();
  16. } else if (Objects.equals(name, LINKED_BLOCKING_DEQUE.getName())) {
  17. blockingQueue = new LinkedBlockingDeque<>(capacity);
  18. } else if (Objects.equals(name, VARIABLE_LINKED_BLOCKING_QUEUE.getName())) {
  19. blockingQueue = new VariableLinkedBlockingQueue<>(capacity);
  20. } else if (Objects.equals(name, MEMORY_SAFE_LINKED_BLOCKING_QUEUE.getName())) {
  21. blockingQueue = new MemorySafeLinkedBlockingQueue<>(capacity, maxFreeMemory * M_1);
  22. }
  23. if (blockingQueue != null) {
  24. return blockingQueue;
  25. }
  26. log.error("Cannot find specified BlockingQueue {}", name);
  27. throw new DtpException("Cannot find specified BlockingQueue " + name);
  28. }

到这里我们已经构造好了创建一个线程池需要的所有参数

调用

  1. BeanUtil#registerIfAbsent()

,先判断是否同名

  1. bean

,如果同名先删除后注入。

  1. @Slf4j
  2. public final class BeanUtil {
  3. private BeanUtil() { }
  4. public static void registerIfAbsent(BeanDefinitionRegistry registry,
  5. String beanName,
  6. Class<?> clazz,
  7. Map<String, Object> properties,
  8. Object... constructorArgs) {
  9. // 如果存在同名bean,先删除后重新注入bean
  10. if (ifPresent(registry, beanName, clazz) || registry.containsBeanDefinition(beanName)) {
  11. log.warn("DynamicTp registrar, bean definition already exists," +
  12. " overrides with remote config, beanName: {}", beanName);
  13. registry.removeBeanDefinition(beanName);
  14. }
  15. doRegister(registry, beanName, clazz, properties, constructorArgs);
  16. }
  17. /**
  18. * 注册Bean 相当于手动用 @Bean 声明线程池对象
  19. * @param registry
  20. * @param beanName
  21. * @param clazz
  22. * @param properties
  23. * @param constructorArgs
  24. */
  25. public static void doRegister(BeanDefinitionRegistry registry,
  26. String beanName,
  27. Class<?> clazz,
  28. Map<String, Object> properties,
  29. Object... constructorArgs) {
  30. BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
  31. for (Object constructorArg : constructorArgs) {
  32. builder.addConstructorArgValue(constructorArg);
  33. }
  34. if (MapUtils.isNotEmpty(properties)) {
  35. properties.forEach(builder::addPropertyValue);
  36. }
  37. // 注册 Bean
  38. registry.registerBeanDefinition(beanName, builder.getBeanDefinition());
  39. }
  40. }

至此线程池对象已经交由

  1. IOC

容器管理了。

我们的线程池对象总不能无脑塞入

  1. IOC

容器就不管了吧,肯定是要留根的,也就是需要一个线程池注册表,记录有哪些线程池是受

  1. dynamic-tp

托管的,这样除了可以进行统计外,也就可以实现通知报警了。

下面我们来看下项目是如何实现注册表的

2.3 注册表

  1. DtpPostProcessor

利用了

  1. Spring

容器启动

  1. BeanPostProcessor

机制增强机制,在

  1. bean

初始化的时候调用

  1. postProcessAfterInitialization

,它实现了获取被

  1. IOC

容器托管的线程池

  1. bean

然后注册到本地的注册表中。

代码实现如下:

  1. @Slf4j
  2. public class DtpPostProcessor implements BeanPostProcessor {
  3. @Override
  4. public Object postProcessAfterInitialization(@NonNull Object bean, @NonNull String beanName)
  5. throws BeansException {
  6. // 只增强线程池相关的类
  7. if (!(bean instanceof ThreadPoolExecutor) && !(bean instanceof ThreadPoolTaskExecutor)) {
  8. return bean;
  9. }
  10. // 如果是 DtpExecutor 类型注册到注册表 DTP_REGISTRY
  11. if (bean instanceof DtpExecutor) {
  12. DtpExecutor dtpExecutor = (DtpExecutor) bean;
  13. if (bean instanceof EagerDtpExecutor) {
  14. ((TaskQueue) dtpExecutor.getQueue()).setExecutor((EagerDtpExecutor) dtpExecutor);
  15. }
  16. registerDtp(dtpExecutor);
  17. return dtpExecutor;
  18. }
  19. // 获取上下文
  20. ApplicationContext applicationContext = ApplicationContextHolder.getInstance();
  21. String dtpAnnotationVal;
  22. try {
  23. // 读取标注 @DynamicTp 注解的 bean 则为基本线程池,但受组件管理监控
  24. DynamicTp dynamicTp = applicationContext.findAnnotationOnBean(beanName, DynamicTp.class);
  25. if (Objects.nonNull(dynamicTp)) {
  26. dtpAnnotationVal = dynamicTp.value();
  27. } else {
  28. BeanDefinitionRegistry registry = (BeanDefinitionRegistry) applicationContext;
  29. AnnotatedBeanDefinition annotatedBeanDefinition =
  30. (AnnotatedBeanDefinition) registry.getBeanDefinition(beanName);
  31. MethodMetadata methodMetadata = (MethodMetadata) annotatedBeanDefinition.getSource();
  32. if (Objects.isNull(methodMetadata)
  33. || !methodMetadata.isAnnotated(DynamicTp.class.getName())) {
  34. return bean;
  35. }
  36. dtpAnnotationVal = Optional.ofNullable(methodMetadata.getAnnotationAttributes(
  37. DynamicTp.class.getName()))
  38. .orElse(Collections.emptyMap())
  39. .getOrDefault("value", "")
  40. .toString();
  41. }
  42. } catch (NoSuchBeanDefinitionException e) {
  43. log.error("There is no bean with the given name {}", beanName, e);
  44. return bean;
  45. }
  46. // 如果说bean上面的DynamicTp注解,使用注解的值作为线程池的名称,没有的话就使用bean的名称
  47. String poolName = StringUtils.isNotBlank(dtpAnnotationVal) ? dtpAnnotationVal : beanName;
  48. if (bean instanceof ThreadPoolTaskExecutor) {
  49. // 注册到注册表 COMMON_REGISTRY
  50. ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) bean;
  51. registerCommon(poolName, taskExecutor.getThreadPoolExecutor());
  52. } else {
  53. registerCommon(poolName, (ThreadPoolExecutor) bean);
  54. }
  55. return bean;
  56. }
  57. /**
  58. * 动态线程池注册 向Map集合put元素
  59. *
  60. * @param executor
  61. */
  62. private void registerDtp(DtpExecutor executor) {
  63. DtpRegistry.registerDtp(executor, "beanPostProcessor");
  64. }
  65. /**
  66. * 非动态线程池注册 向Map集合put元素
  67. *
  68. * @param poolName
  69. * @param executor
  70. */
  71. private void registerCommon(String poolName, ThreadPoolExecutor executor) {
  72. ExecutorWrapper wrapper = new ExecutorWrapper(poolName, executor);
  73. DtpRegistry.registerCommon(wrapper, "beanPostProcessor");
  74. }
  75. }

简单总结下,和刚刚我们分析完全一致

  1. 获取到bean后,如果是非线程池类型则结束。
  2. 如果是DtpExecutor则注册到DTP_REGISTRY注册表中
  3. 如果是非动态线程池且标注了@DynamicTp注解则注册到COMMON_REGISTRY注册表中
  4. 如果是非动态线程池且未标注@DynamicTp注解则结束不做增强
  1. DtpRegistry

主要负责注册、获取、刷新某个动态线程池(刷新线程池我们会下文分析)

  1. @Slf4j
  2. public class DtpRegistry implements ApplicationRunner, Ordered {
  3. /**
  4. * Maintain all automatically registered and manually registered DtpExecutors.
  5. * 动态线程池 key为线程池name
  6. * DtpExecutor ThreadPoolExecutor加强版
  7. */
  8. private static final Map<String, DtpExecutor> DTP_REGISTRY = new ConcurrentHashMap<>();
  9. /**
  10. * Maintain all automatically registered and manually registered JUC ThreadPoolExecutors.
  11. * <p>
  12. * 标有DynamicTp注解的线程池
  13. */
  14. private static final Map<String, ExecutorWrapper> COMMON_REGISTRY = new ConcurrentHashMap<>();
  15. private static final Equator EQUATOR = new GetterBaseEquator();
  16. /**
  17. * 配置文件映射
  18. */
  19. private static DtpProperties dtpProperties;
  20. public static List<String> listAllDtpNames() {
  21. return Lists.newArrayList(DTP_REGISTRY.keySet());
  22. }
  23. public static List<String> listAllCommonNames() {
  24. return Lists.newArrayList(COMMON_REGISTRY.keySet());
  25. }
  26. public static void registerDtp(DtpExecutor executor, String source) {
  27. log.info("DynamicTp register dtpExecutor, source: {}, executor: {}",
  28. source, ExecutorConverter.convert(executor));
  29. DTP_REGISTRY.putIfAbsent(executor.getThreadPoolName(), executor);
  30. }
  31. public static void registerCommon(ExecutorWrapper wrapper, String source) {
  32. log.info("DynamicTp register commonExecutor, source: {}, name: {}",
  33. source, wrapper.getThreadPoolName());
  34. COMMON_REGISTRY.putIfAbsent(wrapper.getThreadPoolName(), wrapper);
  35. }
  36. public static DtpExecutor getDtpExecutor(final String name) {
  37. val executor = DTP_REGISTRY.get(name);
  38. if (Objects.isNull(executor)) {
  39. log.error("Cannot find a specified dtpExecutor, name: {}", name);
  40. throw new DtpException("Cannot find a specified dtpExecutor, name: " + name);
  41. }
  42. return executor;
  43. }
  44. public static ExecutorWrapper getCommonExecutor(final String name) {
  45. val executor = COMMON_REGISTRY.get(name);
  46. if (Objects.isNull(executor)) {
  47. log.error("Cannot find a specified commonExecutor, name: {}", name);
  48. throw new DtpException("Cannot find a specified commonExecutor, name: " + name);
  49. }
  50. return executor;
  51. }
  52. @Autowired
  53. public void setDtpProperties(DtpProperties dtpProperties) {
  54. DtpRegistry.dtpProperties = dtpProperties;
  55. }
  56. @Override
  57. public void run(ApplicationArguments args) {
  58. // 线程池名称
  59. Set<String> remoteExecutors = Collections.emptySet();
  60. // 获取配置文件中配置的线程池
  61. if (CollectionUtils.isNotEmpty(dtpProperties.getExecutors())) {
  62. remoteExecutors = dtpProperties.getExecutors().stream()
  63. .map(ThreadPoolProperties::getThreadPoolName)
  64. .collect(Collectors.toSet());
  65. }
  66. // DTP_REGISTRY中已经注册的线程池
  67. val registeredDtpExecutors = Sets.newHashSet(DTP_REGISTRY.keySet());
  68. // 找出所有线程池中没有在配置文件中配置的线程池
  69. val localDtpExecutors = CollectionUtils.subtract(registeredDtpExecutors, remoteExecutors);
  70. // 日志
  71. log.info("DtpRegistry initialization is complete, remote dtpExecutors: {}," +
  72. " local dtpExecutors: {}, local commonExecutors: {}",
  73. remoteExecutors, localDtpExecutors, COMMON_REGISTRY.keySet());
  74. }
  75. @Override
  76. public int getOrder() {
  77. return Ordered.HIGHEST_PRECEDENCE + 1;
  78. }
  79. }

代码比较简单,这里不再说明了。

流程至此,动态线程池,标注了

  1. @DynamicTp

注解的线程池,都已经准备就绪了。

你可能会问那配置刷新配置刷新动态调参是如何实现的呢,别急,我们继续分析。

2.4 配置刷新 动态调参

  1. Dynamic-tp

提供了配置刷新接口

  1. Refresher

,和基类

  1. AbstractRefresher

,支持不同配置中心的刷新基类,甚至完全可以自行扩展,其原理其实就是当配置中心监听到配置文件的变动后,解析配置文件,刷新配置文件,最后通过

  1. Spring ApplicationListener

机制发送

  1. RefreshEvent

刷新事件,由对应的

  1. Adapter

来处理。

  1. public interface Refresher {
  2. /**
  3. * Refresh with specify content.
  4. *
  5. * @param content content
  6. * @param fileType file type
  7. */
  8. void refresh(String content, ConfigFileTypeEnum fileType);
  9. }
  1. @Slf4j
  2. public abstract class AbstractRefresher implements Refresher {
  3. @Resource
  4. protected DtpProperties dtpProperties;
  5. @Override
  6. public void refresh(String content, ConfigFileTypeEnum fileType) {
  7. if (StringUtils.isBlank(content) || Objects.isNull(fileType)) {
  8. log.warn("DynamicTp refresh, empty content or null fileType.");
  9. return;
  10. }
  11. try {
  12. val configHandler = ConfigHandler.getInstance();
  13. val properties = configHandler.parseConfig(content, fileType);
  14. doRefresh(properties);
  15. } catch (IOException e) {
  16. log.error("DynamicTp refresh error, content: {}, fileType: {}", content, fileType, e);
  17. }
  18. }
  19. protected void doRefresh(Map<Object, Object> properties) {
  20. if (MapUtils.isEmpty(properties)) {
  21. log.warn("DynamicTp refresh, empty properties.");
  22. return;
  23. }
  24. // 将发生变化的属性绑定到DtpProperties对象上
  25. PropertiesBinder.bindDtpProperties(properties, dtpProperties);
  26. // 更新线程池属性
  27. doRefresh(dtpProperties);
  28. }
  29. protected void doRefresh(DtpProperties dtpProperties) {
  30. DtpRegistry.refresh(dtpProperties);
  31. publishEvent(dtpProperties);
  32. }
  33. private void publishEvent(DtpProperties dtpProperties) {
  34. RefreshEvent event = new RefreshEvent(this, dtpProperties);
  35. ApplicationContextHolder.publishEvent(event);
  36. }
  37. }

接下来我们以

  1. Zookeeper

为配置中心举例说明,代码如下。

  1. @Slf4j
  2. public class ZookeeperRefresher extends AbstractRefresher
  3. implements EnvironmentAware, InitializingBean {
  4. @Override
  5. public void afterPropertiesSet() {
  6. final ConnectionStateListener connectionStateListener = (client, newState) -> {
  7. // 连接变更
  8. if (newState == ConnectionState.RECONNECTED) {
  9. loadAndRefresh();
  10. }
  11. };
  12. final CuratorListener curatorListener = (client, curatorEvent) -> {
  13. final WatchedEvent watchedEvent = curatorEvent.getWatchedEvent();
  14. if (null != watchedEvent) {
  15. switch (watchedEvent.getType()) {
  16. // 监听节点变更
  17. case NodeChildrenChanged:
  18. case NodeDataChanged:
  19. // 刷新
  20. loadAndRefresh();
  21. break;
  22. default:
  23. break;
  24. }
  25. }
  26. };
  27. CuratorFramework curatorFramework = CuratorUtil.getCuratorFramework(dtpProperties);
  28. String nodePath = CuratorUtil.nodePath(dtpProperties);
  29. curatorFramework.getConnectionStateListenable().addListener(connectionStateListener);
  30. curatorFramework.getCuratorListenable().addListener(curatorListener);
  31. log.info("DynamicTp refresher, add listener success, nodePath: {}", nodePath);
  32. }
  33. /**
  34. * load config and refresh
  35. */
  36. private void loadAndRefresh() {
  37. doRefresh(CuratorUtil.genPropertiesMap(dtpProperties));
  38. }
  39. @Override
  40. public void setEnvironment(Environment environment) {
  41. ConfigurableEnvironment env = ((ConfigurableEnvironment) environment);
  42. env.getPropertySources().remove(ZK_PROPERTY_SOURCE_NAME);
  43. }
  44. }

利用了

  1. Spring

机制,实现了

  1. InitializingBean

并重写

  1. afterPropertiesSet

,在

  1. Bean

实例化完成之后会被自动调用,在这期间针对

  1. Zookeeper

连接,节点变更监听器进行注册,监听连接变更和节点变更后执行刷新操作。

  1. doRefresh(CuratorUtil.genPropertiesMap(dtpProperties));

实现由基类统一处理,解析配置并绑定

  1. DtpProperties

上,执行

  1. DtpRegistry#refresh()

刷新后发布一个

  1. RefreshEvent

事件。

  1. protected void doRefresh(Map<Object, Object> properties) {
  2. if (MapUtils.isEmpty(properties)) {
  3. log.warn("DynamicTp refresh, empty properties.");
  4. return;
  5. }
  6. // 解析配置并绑定 DtpProperties 上
  7. PropertiesBinder.bindDtpProperties(properties, dtpProperties);
  8. // 更新线程池属性
  9. doRefresh(dtpProperties);
  10. }
  11. protected void doRefresh(DtpProperties dtpProperties) {
  12. DtpRegistry.refresh(dtpProperties);
  13. publishEvent(dtpProperties);
  14. }
  15. private void publishEvent(DtpProperties dtpProperties) {
  16. RefreshEvent event = new RefreshEvent(this, dtpProperties);
  17. ApplicationContextHolder.publishEvent(event);
  18. }

来看

  1. DtpRegistry#refresh()

的实现,代码如下:

  1. public static void refresh(DtpProperties properties) {
  2. if (Objects.isNull(properties) || CollectionUtils.isEmpty(properties.getExecutors())) {
  3. log.warn("DynamicTp refresh, empty threadPoolProperties.");
  4. return;
  5. }
  6. // 属性不为空 从属性中拿到所有的线程池属性配置
  7. properties.getExecutors().forEach(x -> {
  8. if (StringUtils.isBlank(x.getThreadPoolName())) {
  9. log.warn("DynamicTp refresh, threadPoolName must not be empty.");
  10. return;
  11. }
  12. // 从 DTP_REGISTRY 线程注册池表中拿到对应的线程池对象
  13. val dtpExecutor = DTP_REGISTRY.get(x.getThreadPoolName());
  14. if (Objects.isNull(dtpExecutor)) {
  15. log.warn("DynamicTp refresh, cannot find specified dtpExecutor, name: {}.",
  16. x.getThreadPoolName());
  17. return;
  18. }
  19. // 刷新 更新线程池对象
  20. refresh(dtpExecutor, x);
  21. });
  22. }
  1. private static void refresh(DtpExecutor executor, ThreadPoolProperties properties) {
  2. // 参数合法校验
  3. if (properties.getCorePoolSize() < 0
  4. || properties.getMaximumPoolSize() <= 0
  5. || properties.getMaximumPoolSize() < properties.getCorePoolSize()
  6. || properties.getKeepAliveTime() < 0) {
  7. log.error("DynamicTp refresh, invalid parameters exist, properties: {}", properties);
  8. return;
  9. }
  10. // 线程池旧配置
  11. DtpMainProp oldProp = ExecutorConverter.convert(executor);
  12. // 真正开始刷新
  13. doRefresh(executor, properties);
  14. // 线程池新配置
  15. DtpMainProp newProp = ExecutorConverter.convert(executor);
  16. // 相等不作处理
  17. if (oldProp.equals(newProp)) {
  18. log.warn("DynamicTp refresh, main properties of [{}] have not changed.",
  19. executor.getThreadPoolName());
  20. return;
  21. }
  22. List<FieldInfo> diffFields = EQUATOR.getDiffFields(oldProp, newProp);
  23. List<String> diffKeys = diffFields.stream().map(FieldInfo::getFieldName).collect(toList());
  24. // 线程池参数变更 平台提醒
  25. NoticeManager.doNoticeAsync(new ExecutorWrapper(executor), oldProp, diffKeys);
  26. // 更新参数 日志打印
  27. log.info("DynamicTp refresh, name: [{}], changed keys: {}, corePoolSize: [{}]," +
  28. " maxPoolSize: [{}], queueType: [{}], queueCapacity: [{}], keepAliveTime: [{}], " +
  29. "rejectedType: [{}], allowsCoreThreadTimeOut: [{}]",
  30. executor.getThreadPoolName(),
  31. diffKeys,
  32. String.format(PROPERTIES_CHANGE_SHOW_STYLE, oldProp.getCorePoolSize(), newProp.getCorePoolSize()),
  33. String.format(PROPERTIES_CHANGE_SHOW_STYLE, oldProp.getMaxPoolSize(), newProp.getMaxPoolSize()),
  34. String.format(PROPERTIES_CHANGE_SHOW_STYLE, oldProp.getQueueType(), newProp.getQueueType()),
  35. String.format(PROPERTIES_CHANGE_SHOW_STYLE, oldProp.getQueueCapacity(), newProp.getQueueCapacity()),
  36. String.format("%ss => %ss", oldProp.getKeepAliveTime(), newProp.getKeepAliveTime()),
  37. String.format(PROPERTIES_CHANGE_SHOW_STYLE, oldProp.getRejectType(), newProp.getRejectType()),
  38. String.format(PROPERTIES_CHANGE_SHOW_STYLE, oldProp.isAllowCoreThreadTimeOut(),
  39. newProp.isAllowCoreThreadTimeOut()));
  40. }

总结一下上述代码无非做了这么几件事

  1. 参数合法校验
  2. 获取到线程池旧配置
  3. 执行刷新
  4. 获取到线程池新配置
  5. 如果新旧配置相同,则证明没有改动,不做处理
  6. 否则线程池变更发送通知,并记录变更日志(ps:通知相关处理下文会说,这里先跳过)
  1. doRefresh

真正执行线程池的刷新,也依靠于

  1. JUC

原生线程池支持动态属性变更。

  1. private static void doRefresh(DtpExecutor dtpExecutor, ThreadPoolProperties properties) {
  2. // 调用相应的setXXX方法更新线程池参数
  3. doRefreshPoolSize(dtpExecutor, properties);
  4. if (!Objects.equals(dtpExecutor.getKeepAliveTime(properties.getUnit()),
  5. properties.getKeepAliveTime())) {
  6. dtpExecutor.setKeepAliveTime(properties.getKeepAliveTime(), properties.getUnit());
  7. }
  8. if (!Objects.equals(dtpExecutor.allowsCoreThreadTimeOut(),
  9. properties.isAllowCoreThreadTimeOut())) {
  10. dtpExecutor.allowCoreThreadTimeOut(properties.isAllowCoreThreadTimeOut());
  11. }
  12. // update reject handler
  13. if (!Objects.equals(dtpExecutor.getRejectHandlerName(),
  14. properties.getRejectedHandlerType())) {
  15. dtpExecutor.setRejectedExecutionHandler(RejectHandlerGetter.getProxy(
  16. properties.getRejectedHandlerType()));
  17. dtpExecutor.setRejectHandlerName(properties.getRejectedHandlerType());
  18. }
  19. // update Alias Name
  20. if (!Objects.equals(dtpExecutor.getThreadPoolAliasName(), properties.getThreadPoolAliasName())) {
  21. dtpExecutor.setThreadPoolAliasName(properties.getThreadPoolAliasName());
  22. }
  23. updateQueueProp(properties, dtpExecutor);
  24. dtpExecutor.setWaitForTasksToCompleteOnShutdown(properties.isWaitForTasksToCompleteOnShutdown());
  25. dtpExecutor.setAwaitTerminationSeconds(properties.getAwaitTerminationSeconds());
  26. dtpExecutor.setPreStartAllCoreThreads(properties.isPreStartAllCoreThreads());
  27. dtpExecutor.setRunTimeout(properties.getRunTimeout());
  28. dtpExecutor.setQueueTimeout(properties.getQueueTimeout());
  29. List<TaskWrapper> taskWrappers = TaskWrappers.getInstance().getByNames(
  30. properties.getTaskWrapperNames());
  31. dtpExecutor.setTaskWrappers(taskWrappers);
  32. // update notify items
  33. val allNotifyItems = mergeAllNotifyItems(properties.getNotifyItems());
  34. // 刷新通知平台
  35. NotifyHelper.refreshNotify(dtpExecutor.getThreadPoolName(), dtpProperties.getPlatforms(),
  36. dtpExecutor.getNotifyItems(), allNotifyItems);
  37. dtpExecutor.setNotifyItems(allNotifyItems);
  38. dtpExecutor.setNotifyEnabled(properties.isNotifyEnabled());
  39. }
  1. doRefreshPoolSize

调用

  1. ThreadPoolExecutor

原生

  1. setXXX

方法支持在运行时动态修改

  1. private static void doRefreshPoolSize(ThreadPoolExecutor dtpExecutor,
  2. ThreadPoolProperties properties) {
  3. // 调用ThreadPoolExecutor原生setXXX方法 支持在运行时动态修改
  4. if (properties.getMaximumPoolSize() < dtpExecutor.getMaximumPoolSize()) {
  5. if (!Objects.equals(dtpExecutor.getCorePoolSize(), properties.getCorePoolSize())) {
  6. dtpExecutor.setCorePoolSize(properties.getCorePoolSize());
  7. }
  8. if (!Objects.equals(dtpExecutor.getMaximumPoolSize(), properties.getMaximumPoolSize())) {
  9. dtpExecutor.setMaximumPoolSize(properties.getMaximumPoolSize());
  10. }
  11. return;
  12. }
  13. if (!Objects.equals(dtpExecutor.getMaximumPoolSize(), properties.getMaximumPoolSize())) {
  14. dtpExecutor.setMaximumPoolSize(properties.getMaximumPoolSize());
  15. }
  16. if (!Objects.equals(dtpExecutor.getCorePoolSize(), properties.getCorePoolSize())) {
  17. dtpExecutor.setCorePoolSize(properties.getCorePoolSize());
  18. }
  19. }
  1. updateQueueProp

更新线程池阻塞队列大小

  1. private static void updateQueueProp(ThreadPoolProperties properties, DtpExecutor dtpExecutor) {
  2. // queueType 非 VariableLinkedBlockingQueue MemorySafeLinkedBlockingQueue
  3. // 且executorType为EagerDtpExecutor 不刷新
  4. if (!canModifyQueueProp(properties)) {
  5. return;
  6. }
  7. // 获取到线程池原来的队列
  8. val blockingQueue = dtpExecutor.getQueue();
  9. // 如果原来的队列容量和现在的不一样
  10. if (!Objects.equals(dtpExecutor.getQueueCapacity(), properties.getQueueCapacity())) {
  11. // 并且原来的队列是 VariableLinkedBlockingQueue 类型的,那么就设置队列的容量
  12. if (blockingQueue instanceof VariableLinkedBlockingQueue) {
  13. ((VariableLinkedBlockingQueue<Runnable>) blockingQueue)
  14. .setCapacity(properties.getQueueCapacity());
  15. } else {
  16. // 否则不设置
  17. log.error("DynamicTp refresh, the blockingqueue capacity cannot be reset, dtpName: {}," +
  18. " queueType {}", dtpExecutor.getThreadPoolName(), dtpExecutor.getQueueName());
  19. }
  20. }
  21. // 如果队列是 MemorySafeLinkedBlockingQueue,那么设置最大内存
  22. if (blockingQueue instanceof MemorySafeLinkedBlockingQueue) {
  23. ((MemorySafeLinkedBlockingQueue<Runnable>) blockingQueue)
  24. .setMaxFreeMemory(properties.getMaxFreeMemory() * M_1);
  25. }
  26. }

上述代码提到了几个眼生的队列,他们都是

  1. dynamic-tp

自行实现的阻塞队列,我们来看下

  1. VariableLinkedBlockingQueue

: 可以设置队列容量,且支持变更队列容量

  1. MemorySafeLinkedBlockingQueue

: 继承

  1. VariableLinkedBlockingQueue

,可以通过

  1. maxFreeMemory

设置队列容量,在构造器中对容量有默认的大小限制

**首先我们思考一下,为什么

  1. dynamic-tp

要自行实现的阻塞队列?**

当你翻看

  1. Java

原生

  1. LinkedBlockingQueue

队列时你就会发现,队列容量被定义为

  1. private final

类型的,不能修改,那肯定是不符合我们修改阻塞队列大小还能实现刷新线程池的效果。

其中着重说明下

  1. MemorySafeLinkedBlockingQueue

队列,

  1. LinkedBlockingQueue

的容量默认是

  1. Integer.MAX_VALUE

,所以当我们不对其进行限制时,就有可能导致

  1. OOM

问题,所以

  1. MemorySafeLinkedBlockingQueue

构造函数设置了默认队列大小

当我们往队列添加元素的时候,会先判断有没有足够的空间

  1. public class MemorySafeLinkedBlockingQueue<E> extends VariableLinkedBlockingQueue<E> {
  2. private static final long serialVersionUID = 8032578371739960142L;
  3. public static final int THE_256_MB = 256 * 1024 * 1024;
  4. /**
  5. * 队列的容量
  6. */
  7. private int maxFreeMemory;
  8. public MemorySafeLinkedBlockingQueue() {
  9. // 默认256MB
  10. this(THE_256_MB);
  11. }
  12. public MemorySafeLinkedBlockingQueue(final int maxFreeMemory) {
  13. super(Integer.MAX_VALUE);
  14. this.maxFreeMemory = maxFreeMemory;
  15. }
  16. public MemorySafeLinkedBlockingQueue(final int capacity, final int maxFreeMemory) {
  17. super(capacity);
  18. this.maxFreeMemory = maxFreeMemory;
  19. }
  20. public MemorySafeLinkedBlockingQueue(final Collection<? extends E> c, final int maxFreeMemory) {
  21. super(c);
  22. this.maxFreeMemory = maxFreeMemory;
  23. }
  24. /**
  25. * set the max free memory.
  26. *
  27. * @param maxFreeMemory the max free memory
  28. */
  29. public void setMaxFreeMemory(final int maxFreeMemory) {
  30. this.maxFreeMemory = maxFreeMemory;
  31. }
  32. /**
  33. * get the max free memory.
  34. *
  35. * @return the max free memory limit
  36. */
  37. public int getMaxFreeMemory() {
  38. return maxFreeMemory;
  39. }
  40. /**
  41. * determine if there is any remaining free memory.
  42. *
  43. * @return true if has free memory
  44. */
  45. public boolean hasRemainedMemory() {
  46. if (MemoryLimitCalculator.maxAvailable() > maxFreeMemory) {
  47. return true;
  48. }
  49. throw new RejectedExecutionException("No more memory can be used.");
  50. }
  51. @Override
  52. public void put(final E e) throws InterruptedException {
  53. // 我们往队列添加元素的时候,会先判断有没有足够的空间
  54. if (hasRemainedMemory()) {
  55. super.put(e);
  56. }
  57. }
  58. @Override
  59. public boolean offer(final E e, final long timeout, final TimeUnit unit)
  60. throws InterruptedException {
  61. return hasRemainedMemory() && super.offer(e, timeout, unit);
  62. }
  63. @Override
  64. public boolean offer(final E e) {
  65. return hasRemainedMemory() && super.offer(e);
  66. }
  67. }

回到上文我们说刷新完线程池后,发送异步事件

  1. RefreshEvent

,来继续看下

  1. DtpAdapterListener

处于

  1. adapter

模块,该模块主要是对些三方组件中的线程池进行管理(例如

  1. Tomcat

  1. Jetty

等),通过

  1. spring

的事件发布监听机制来实现与核心流程解耦

  1. @Slf4j
  2. public class DtpAdapterListener implements GenericApplicationListener {
  3. @Override
  4. public boolean supportsEventType(ResolvableType resolvableType) {
  5. Class<?> type = resolvableType.getRawClass();
  6. if (type != null) {
  7. return RefreshEvent.class.isAssignableFrom(type)
  8. || CollectEvent.class.isAssignableFrom(type)
  9. || AlarmCheckEvent.class.isAssignableFrom(type);
  10. }
  11. return false;
  12. }
  13. @Override
  14. public void onApplicationEvent(@NonNull ApplicationEvent event) {
  15. try {
  16. if (event instanceof RefreshEvent) {
  17. doRefresh(((RefreshEvent) event).getDtpProperties());
  18. } else if (event instanceof CollectEvent) {
  19. doCollect(((CollectEvent) event).getDtpProperties());
  20. } else if (event instanceof AlarmCheckEvent) {
  21. doAlarmCheck(((AlarmCheckEvent) event).getDtpProperties());
  22. }
  23. } catch (Exception e) {
  24. log.error("DynamicTp adapter, event handle failed.", e);
  25. }
  26. }
  27. }
  1. /**
  2. * Do refresh.
  3. *
  4. * @param dtpProperties dtpProperties
  5. */
  6. protected void doRefresh(DtpProperties dtpProperties) {
  7. val handlerMap = ApplicationContextHolder.getBeansOfType(DtpAdapter.class);
  8. if (CollectionUtils.isEmpty(handlerMap)) {
  9. return;
  10. }
  11. handlerMap.forEach((k, v) -> v.refresh(dtpProperties));
  12. }

2.3 线程池类型

DtpLifecycleSupport

  1. DtpLifecycleSupport

继承了

  1. JUC ThreadPoolExecutor

,对原生线程池进行了增强

  1. @Slf4j
  2. public abstract class DtpLifecycleSupport extends ThreadPoolExecutor
  3. implements InitializingBean, DisposableBean {
  4. protected String threadPoolName;
  5. /**
  6. * Whether to wait for scheduled tasks to complete on shutdown,
  7. * not interrupting running tasks and executing all tasks in the queue.
  8. * <p>
  9. * 在关闭线程池的时候是否等待任务执行完毕,不会打断运行中的任务,并且会执行队列中的所有任务
  10. */
  11. protected boolean waitForTasksToCompleteOnShutdown = false;
  12. /**
  13. * The maximum number of seconds that this executor is supposed to block
  14. * on shutdown in order to wait for remaining tasks to complete their execution
  15. * before the rest of the container continues to shut down.
  16. * <p>
  17. * 在线程池关闭时等待的最大时间,目的就是等待线程池中的任务运行完毕。
  18. */
  19. protected int awaitTerminationSeconds = 0;
  20. public DtpLifecycleSupport(int corePoolSize,
  21. int maximumPoolSize,
  22. long keepAliveTime,
  23. TimeUnit unit,
  24. BlockingQueue<Runnable> workQueue,
  25. ThreadFactory threadFactory) {
  26. super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
  27. }
  28. @Override
  29. public void afterPropertiesSet() {
  30. DtpProperties dtpProperties = ApplicationContextHolder.getBean(DtpProperties.class);
  31. // 子类实现
  32. initialize(dtpProperties);
  33. }
  34. }

提供了两个增强字段

  1. waitForTasksToCompleteOnShutdown

  1. awaitTerminationSeconds

我们以此来看下

  1. waitForTasksToCompleteOnShutdown

作用在线程池销毁阶段

  1. public void internalShutdown() {
  2. if (log.isInfoEnabled()) {
  3. log.info("Shutting down ExecutorService, poolName: {}", threadPoolName);
  4. }
  5. // 如果需要等待任务执行完毕,则调用 shutdown()会执行先前已提交的任务,拒绝新任务提交,线程池状态变成 SHUTDOWN
  6. if (this.waitForTasksToCompleteOnShutdown) {
  7. this.shutdown();
  8. } else {
  9. // 如果不需要等待任务执行完毕,则直接调用shutdownNow()方法,尝试中断正在执行的任务,
  10. // 返回所有未执行的任务,线程池状态变成 STOP, 然后调用 Future 的 cancel 方法取消
  11. for (Runnable remainingTask : this.shutdownNow()) {
  12. cancelRemainingTask(remainingTask);
  13. }
  14. }
  15. awaitTerminationIfNecessary();
  16. }

总结下它的作用就是在关闭线程池的时候看是否等待任务执行完毕,如果需要等待则会拒绝新任务的提交,执行先前已提交的任务,否则中断正在执行的任务。

  1. awaitTerminationSeconds

字段主要是配合

  1. shutdown

使用,阻塞当前线程,等待已提交的任务执行完毕或者超时的最大时间,等待线程池中的任务运行结束。

DtpExecutor

  1. DtpExecutor

也就是我们项目中横贯整个流程的动态线程池,它继承自

  1. DtpLifecycleSupport

,主要是也是实现对基本线程池的增强。

  1. @Slf4j
  2. public class DtpExecutor extends DtpLifecycleSupport implements SpringExecutor {
  3. /**
  4. * Simple Business alias Name of Dynamic ThreadPool. Use for notify.
  5. */
  6. private String threadPoolAliasName;
  7. /**
  8. * RejectHandler name.
  9. */
  10. private String rejectHandlerName;
  11. /**
  12. * If enable notify.
  13. */
  14. private boolean notifyEnabled;
  15. /**
  16. * Notify items, see {@link NotifyItemEnum}.
  17. * <p>
  18. * 需要提醒的平台
  19. */
  20. private List<NotifyItem> notifyItems;
  21. /**
  22. * Task wrappers, do sth enhanced.
  23. */
  24. private List<TaskWrapper> taskWrappers = Lists.newArrayList();
  25. /**
  26. * If pre start all core threads.
  27. * <p>
  28. * 线程是否需要提前预热,真正调用的还是ThreadPoolExecutor的对应方法
  29. */
  30. private boolean preStartAllCoreThreads;
  31. /**
  32. * Task execute timeout, unit (ms), just for statistics.
  33. */
  34. private long runTimeout;
  35. /**
  36. * Task queue wait timeout, unit (ms), just for statistics.
  37. */
  38. private long queueTimeout;
  39. /**
  40. * Total reject count.
  41. */
  42. private final LongAdder rejectCount = new LongAdder();
  43. /**
  44. * Count run timeout tasks.
  45. */
  46. private final LongAdder runTimeoutCount = new LongAdder();
  47. /**
  48. * Count queue wait timeout tasks.
  49. */
  50. private final LongAdder queueTimeoutCount = new LongAdder();
  51. public DtpExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime,
  52. TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
  53. RejectedExecutionHandler handler) {
  54. super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
  55. this.rejectHandlerName = handler.getClass().getSimpleName();
  56. setRejectedExecutionHandler(RejectHandlerGetter.getProxy(handler));
  57. }
  58. @Override
  59. public void execute(Runnable task, long startTimeout) {
  60. execute(task);
  61. }
  62. /**
  63. * 增强方法
  64. *
  65. * @param command the runnable task
  66. */
  67. @Override
  68. public void execute(Runnable command) {
  69. String taskName = null;
  70. if (command instanceof NamedRunnable) {
  71. taskName = ((NamedRunnable) command).getName();
  72. }
  73. if (CollectionUtils.isNotEmpty(taskWrappers)) {
  74. for (TaskWrapper t : taskWrappers) {
  75. command = t.wrap(command);
  76. }
  77. }
  78. if (runTimeout > 0 || queueTimeout > 0) {
  79. command = new DtpRunnable(command, taskName);
  80. }
  81. super.execute(command);
  82. }
  83. /**
  84. * 增强方法
  85. *
  86. * @param t the thread that will run task {@code r}
  87. * @param r the task that will be executed
  88. */
  89. @Override
  90. protected void beforeExecute(Thread t, Runnable r) {
  91. if (!(r instanceof DtpRunnable)) {
  92. super.beforeExecute(t, r);
  93. return;
  94. }
  95. DtpRunnable runnable = (DtpRunnable) r;
  96. long currTime = TimeUtil.currentTimeMillis();
  97. if (runTimeout > 0) {
  98. runnable.setStartTime(currTime);
  99. }
  100. if (queueTimeout > 0) {
  101. long waitTime = currTime - runnable.getSubmitTime();
  102. if (waitTime > queueTimeout) {
  103. queueTimeoutCount.increment();
  104. AlarmManager.doAlarmAsync(this, QUEUE_TIMEOUT);
  105. if (StringUtils.isNotBlank(runnable.getTaskName())) {
  106. log.warn("DynamicTp execute, queue timeout, poolName: {}, " +
  107. "taskName: {}, waitTime: {}ms", this.getThreadPoolName(),
  108. runnable.getTaskName(), waitTime);
  109. }
  110. }
  111. }
  112. super.beforeExecute(t, r);
  113. }
  114. /**
  115. * 增强方法
  116. *
  117. * @param r the runnable that has completed
  118. * @param t the exception that caused termination, or null if
  119. * execution completed normally
  120. */
  121. @Override
  122. protected void afterExecute(Runnable r, Throwable t) {
  123. if (runTimeout > 0) {
  124. DtpRunnable runnable = (DtpRunnable) r;
  125. long runTime = TimeUtil.currentTimeMillis() - runnable.getStartTime();
  126. if (runTime > runTimeout) {
  127. runTimeoutCount.increment();
  128. AlarmManager.doAlarmAsync(this, RUN_TIMEOUT);
  129. if (StringUtils.isNotBlank(runnable.getTaskName())) {
  130. log.warn("DynamicTp execute, run timeout, poolName: {}," +
  131. " taskName: {}, runTime: {}ms", this.getThreadPoolName(),
  132. runnable.getTaskName(), runTime);
  133. }
  134. }
  135. }
  136. super.afterExecute(r, t);
  137. }
  138. @Override
  139. protected void initialize(DtpProperties dtpProperties) {
  140. NotifyHelper.initNotify(this, dtpProperties.getPlatforms());
  141. if (preStartAllCoreThreads) {
  142. // 在没有任务到来之前就创建corePoolSize个线程或一个线程 因为在默认线程池启动的时候是不会启动核心线程的,
  143. // 只有来了新的任务时才会启动线程
  144. prestartAllCoreThreads();
  145. }
  146. }
  147. }

EagerDtpExecutor

  1. EagerDtpExecutor

继承了

  1. DtpExecutor

,专为

  1. IO

密集场景提供,为什么这么说呢,请看下文分析

  1. public class EagerDtpExecutor extends DtpExecutor {
  2. /**
  3. * The number of tasks submitted but not yet finished.
  4. * 已经提交的但还没有完成的任务数量
  5. */
  6. private final AtomicInteger submittedTaskCount = new AtomicInteger(0);
  7. public EagerDtpExecutor(int corePoolSize,
  8. int maximumPoolSize,
  9. long keepAliveTime,
  10. TimeUnit unit,
  11. BlockingQueue<Runnable> workQueue,
  12. ThreadFactory threadFactory,
  13. RejectedExecutionHandler handler) {
  14. super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
  15. }
  16. public int getSubmittedTaskCount() {
  17. return submittedTaskCount.get();
  18. }
  19. @Override
  20. protected void afterExecute(Runnable r, Throwable t) {
  21. submittedTaskCount.decrementAndGet();
  22. super.afterExecute(r, t);
  23. }
  24. @Override
  25. public void execute(Runnable command) {
  26. if (command == null) {
  27. throw new NullPointerException();
  28. }
  29. submittedTaskCount.incrementAndGet();
  30. try {
  31. super.execute(command);
  32. } catch (RejectedExecutionException rx) {
  33. // 被拒绝时
  34. if (getQueue() instanceof TaskQueue) {
  35. // If the Executor is close to maximum pool size, concurrent
  36. // calls to execute() may result (due to use of TaskQueue) in
  37. // some tasks being rejected rather than queued.
  38. // If this happens, add them to the queue.
  39. final TaskQueue queue = (TaskQueue) getQueue();
  40. try {
  41. // 加入队列中
  42. if (!queue.force(command, 0, TimeUnit.MILLISECONDS)) {
  43. submittedTaskCount.decrementAndGet();
  44. throw new RejectedExecutionException("Queue capacity is full.", rx);
  45. }
  46. } catch (InterruptedException x) {
  47. submittedTaskCount.decrementAndGet();
  48. throw new RejectedExecutionException(x);
  49. }
  50. } else {
  51. submittedTaskCount.decrementAndGet();
  52. throw rx;
  53. }
  54. }
  55. }
  56. }

来看

  1. execute

执行方法,当捕获住拒绝异常时,说明线程池队列已满且大于最大线程数,如果当前队列是

  1. TaskQueue

则重新将拒绝任务加入队列中,加入失败则抛出任务拒绝异常。

来看TaskQueue代码实现

  1. public class TaskQueue extends VariableLinkedBlockingQueue<Runnable> {
  2. private static final long serialVersionUID = -1L;
  3. private transient EagerDtpExecutor executor;
  4. public TaskQueue(int queueCapacity) {
  5. super(queueCapacity);
  6. }
  7. public void setExecutor(EagerDtpExecutor exec) {
  8. executor = exec;
  9. }
  10. @Override
  11. public boolean offer(@NonNull Runnable runnable) {
  12. if (executor == null) {
  13. throw new RejectedExecutionException("The task queue does not have executor.");
  14. }
  15. int currentPoolThreadSize = executor.getPoolSize();
  16. // 线程池中的线程数等于最大线程数的时候,就将任务放进队列等待工作线程处理
  17. if (currentPoolThreadSize == executor.getMaximumPoolSize()) {
  18. return super.offer(runnable);
  19. }
  20. // 如果当前未执行的任务数量小于等于当前线程数,还有剩余的worker线程,就将任务放进队列等待工作线程处理
  21. if (executor.getSubmittedTaskCount() < currentPoolThreadSize) {
  22. return super.offer(runnable);
  23. }
  24. // 如果当前线程数大于核心线程,但小于最大线程数量,则直接返回false,外层逻辑线程池创建新的线程来执行任务
  25. if (currentPoolThreadSize < executor.getMaximumPoolSize()) {
  26. return false;
  27. }
  28. // currentPoolThreadSize >= max
  29. return super.offer(runnable);
  30. }
  31. }

上述代码我们看到

  1. currentPoolThreadSize < executor.getMaximumPoolSize()

会返回

  1. false

底层实现还是

  1. JUC

  1. ThreadPoolExecutor

,来看

  1. execute

方法,当前线程数大于核心线程,但小于最大线程数量,则执行

  1. addWorker(command, false)

,创建新的线程来执行任务。

  1. public void execute(Runnable command) {
  2. if (command == null)
  3. throw new NullPointerException();
  4. // 线程池状态和线程数的整数
  5. int c = ctl.get();
  6. // 如果当前线程数小于核心线程数,创建 Worker 线程并启动线程
  7. if (workerCountOf(c) < corePoolSize) {
  8. // 添加任务成功,那么就结束了 结果会包装到 FutureTask 中
  9. if (addWorker(command, true))
  10. return;
  11. c = ctl.get();
  12. }
  13. // 要么当前线程数大于等于核心线程数,要么刚刚addWorker失败了,如果线程池处于RUNNING状态,
  14. // 把这个任务添加到任务队列 workQueue 中
  15. if (isRunning(c) && workQueue.offer(command)) {
  16. // 二次状态检查
  17. int recheck = ctl.get();
  18. // 如果线程池已不处于 RUNNING 状态,那么移除已经入队的这个任务,并且执行拒绝策略
  19. if (! isRunning(recheck) && remove(command))
  20. reject(command);
  21. // 如果线程池还是 RUNNING 的,并且线程数为 0,重新创建一个新的线程 这里目的担心任务提交到队列中了,但是线程都关闭了
  22. else if (workerCountOf(recheck) == 0)
  23. // 创建Worker,并启动里面的Thread,为什么传null,线程启动后会自动从阻塞队列拉任务执行
  24. addWorker(null, false);
  25. }
  26. // workQueue.offer(command)返回false,以 maximumPoolSize 为界创建新的 worker线程并启动线程,
  27. // 如果失败,说明当前线程数已经达到 maximumPoolSize,执行拒绝策略
  28. else if (!addWorker(command, false))
  29. reject(command);
  30. }

一看这不就是

  1. Tomcat

线程池处理流程吗,对比于原生

  1. JUC

线程池提交任务流程

**看下原生

  1. JUC

线程池提交任务的流程**

  • 当前线程数小于核心线程数,则创建一个新的线程来执行任务
  • 当前线程数大于等于核心线程数,且阻塞队列未满,则将任务添加到队列中
  • 如果阻塞队列已满,当前线程数大于等于核心线程数,当前线程数小于最大线程数,则创建并启动一个线程来执行新提交的任务
  • 若当前线程数大于等于最大线程数,且阻塞队列已满,此时会执行拒绝策略

来看下原生

  1. JUC

线程池提交流程,引用美团线程池篇中的图

原生

  1. JUC

线程池核心思想就是就是先让核心线程数的线程工作,多余的任务统统塞到阻塞队列,阻塞队列塞不下才再多创建线程来工作,这种情况下当大量请求提交时,大量的请求很有可能都会被阻塞在队列中,而线程还没有创建到最大线程数,导致用户请求处理很慢用户体验很差。

那如何解决呢?

重写了

  1. execute()

方法,当抛出拒绝策略了尝试一次往阻塞队列里插入任务,尽最大努力的去执行任务,新增阻塞队列继承了

  1. LinkedBlockingQueue

,重写了

  1. offer()

方法,重写了

  1. offer()

方法,每次向队列插入任务,判断如果当前线程数小于最大线程数则插入失败。进而让线程池创建新线程来处理任务。

如下图所示:

总结:知识是相通的,要学以致用

2.4 报警通知

关于分析报警通知,可以从

  1. AlarmManager

  1. NoticeManager

这两个类入手,实际就是分别构造了一个报警通知责任链,在需要报警通知的时候,调用责任链执行。

先来看

  1. AlarmManager

的代码实现

  1. @Slf4j
  2. public class AlarmManager {
  3. private static final ExecutorService ALARM_EXECUTOR = ThreadPoolBuilder.newBuilder()
  4. .threadPoolName("dtp-alarm")
  5. .threadFactory("dtp-alarm")
  6. .corePoolSize(2)
  7. .maximumPoolSize(4)
  8. .workQueue(LINKED_BLOCKING_QUEUE.getName(), 2000, false, null)
  9. .rejectedExecutionHandler(RejectedTypeEnum.DISCARD_OLDEST_POLICY.getName())
  10. .buildCommon();
  11. private static final InvokerChain<BaseNotifyCtx> ALARM_INVOKER_CHAIN;
  12. static {
  13. // 构造责任链
  14. ALARM_INVOKER_CHAIN = NotifyFilterBuilder.getAlarmInvokerChain();
  15. }
  16. private AlarmManager() {
  17. }
  18. }

责任链的构造

  1. public class NotifyFilterBuilder {
  2. private NotifyFilterBuilder() { }
  3. public static InvokerChain<BaseNotifyCtx> getAlarmInvokerChain() {
  4. val filters = ApplicationContextHolder.getBeansOfType(NotifyFilter.class);
  5. Collection<NotifyFilter> alarmFilters = Lists.newArrayList(filters.values());
  6. alarmFilters.add(new AlarmBaseFilter());
  7. alarmFilters = alarmFilters.stream()
  8. .filter(x -> x.supports(NotifyTypeEnum.ALARM))
  9. .sorted(Comparator.comparing(Filter::getOrder))
  10. .collect(Collectors.toList());
  11. // 构造ALARM_FILTER_CHAIN链
  12. return InvokerChainFactory.buildInvokerChain(new AlarmInvoker(),
  13. alarmFilters.toArray(new NotifyFilter[0]));
  14. }
  15. public static InvokerChain<BaseNotifyCtx> getCommonInvokerChain() {
  16. val filters = ApplicationContextHolder.getBeansOfType(NotifyFilter.class);
  17. Collection<NotifyFilter> noticeFilters = Lists.newArrayList(filters.values());
  18. noticeFilters.add(new NoticeBaseFilter());
  19. noticeFilters = noticeFilters.stream()
  20. .filter(x -> x.supports(NotifyTypeEnum.COMMON))
  21. .sorted(Comparator.comparing(Filter::getOrder))
  22. .collect(Collectors.toList());
  23. return InvokerChainFactory.buildInvokerChain(new NoticeInvoker(),
  24. noticeFilters.toArray(new NotifyFilter[0]));
  25. }
  26. }
  1. public final class InvokerChainFactory {
  2. private InvokerChainFactory() { }
  3. @SafeVarargs
  4. public static<T> InvokerChain<T> buildInvokerChain(Invoker<T> target, Filter<T>... filters) {
  5. InvokerChain<T> invokerChain = new InvokerChain<>();
  6. Invoker<T> last = target;
  7. for (int i = filters.length - 1; i >= 0; i--) {
  8. Invoker<T> next = last;
  9. Filter<T> filter = filters[i];
  10. last = context -> filter.doFilter(context, next);
  11. }
  12. invokerChain.setHead(last);
  13. return invokerChain;
  14. }
  15. }

执行报警方法调用如下

  1. public static void doAlarm(ExecutorWrapper executorWrapper, NotifyItemEnum notifyItemEnum) {
  2. // 根据告警类型获取告警项配置,一个线程池可以配置多个NotifyItem,这里需要过滤
  3. NotifyHelper.getNotifyItem(executorWrapper, notifyItemEnum).ifPresent(notifyItem -> {
  4. // 执行责任链
  5. val alarmCtx = new AlarmCtx(executorWrapper, notifyItem);
  6. ALARM_INVOKER_CHAIN.proceed(alarmCtx);
  7. });
  8. }

执行责任链,真正执行报警通知的代码如下

  1. public class AlarmInvoker implements Invoker<BaseNotifyCtx> {
  2. @Override
  3. public void invoke(BaseNotifyCtx context) {
  4. val alarmCtx = (AlarmCtx) context;
  5. val executorWrapper = alarmCtx.getExecutorWrapper();
  6. val notifyItem = alarmCtx.getNotifyItem();
  7. val alarmInfo = AlarmCounter.getAlarmInfo(executorWrapper.getThreadPoolName(),
  8. notifyItem.getType());
  9. alarmCtx.setAlarmInfo(alarmInfo);
  10. DtpNotifyCtxHolder.set(context);
  11. // 真正的发送告警的逻辑
  12. NotifierHandler.getInstance().sendAlarm(NotifyItemEnum.of(notifyItem.getType()));
  13. AlarmCounter.reset(executorWrapper.getThreadPoolName(), notifyItem.getType());
  14. }
  15. }

调用NotifierHandler#sendAlarm()

  1. @Slf4j
  2. public final class NotifierHandler {
  3. private static final Map<String, DtpNotifier> NOTIFIERS = new HashMap<>();
  4. private NotifierHandler() {
  5. ServiceLoader<DtpNotifier> loader = ServiceLoader.load(DtpNotifier.class);
  6. for (DtpNotifier notifier : loader) {
  7. NOTIFIERS.put(notifier.platform(), notifier);
  8. }
  9. DtpNotifier dingNotifier = new DtpDingNotifier(new DingNotifier());
  10. DtpNotifier wechatNotifier = new DtpWechatNotifier(new WechatNotifier());
  11. DtpNotifier larkNotifier = new DtpLarkNotifier(new LarkNotifier());
  12. NOTIFIERS.put(dingNotifier.platform(), dingNotifier);
  13. NOTIFIERS.put(wechatNotifier.platform(), wechatNotifier);
  14. NOTIFIERS.put(larkNotifier.platform(), larkNotifier);
  15. }
  16. public void sendAlarm(NotifyItemEnum notifyItemEnum) {
  17. try {
  18. NotifyItem notifyItem = DtpNotifyCtxHolder.get().getNotifyItem();
  19. for (String platform : notifyItem.getPlatforms()) {
  20. DtpNotifier notifier = NOTIFIERS.get(platform.toLowerCase());
  21. if (notifier != null) {
  22. notifier.sendAlarmMsg(notifyItemEnum);
  23. }
  24. }
  25. } finally {
  26. DtpNotifyCtxHolder.remove();
  27. }
  28. }
  29. }

最后调用notifier.sendAlarmMsg(notifyItemEnum)发送消息

  1. @Override
  2. public void sendAlarmMsg(NotifyItemEnum notifyItemEnum) {
  3. NotifyHelper.getPlatform(platform()).ifPresent(platform -> {
  4. // 构建报警信息
  5. String content = buildAlarmContent(platform, notifyItemEnum);
  6. if (StringUtils.isBlank(content)) {
  7. return;
  8. }
  9. // 发送
  10. notifier.send(platform, content);
  11. });
  12. }

2.5 监控

入口DtpMonitor

  1. @Slf4j
  2. public class DtpMonitor implements ApplicationRunner, Ordered {
  3. private static final ScheduledExecutorService MONITOR_EXECUTOR = new ScheduledThreadPoolExecutor(
  4. 1, new NamedThreadFactory("dtp-monitor", true));
  5. @Resource
  6. private DtpProperties dtpProperties;
  7. /**
  8. * 每隔 monitorInterval(默认为5) 执行监控
  9. *
  10. * @param args
  11. */
  12. @Override
  13. public void run(ApplicationArguments args) {
  14. MONITOR_EXECUTOR.scheduleWithFixedDelay(this::run,
  15. 0, dtpProperties.getMonitorInterval(), TimeUnit.SECONDS);
  16. }
  17. private void run() {
  18. // 所有线程池的名称
  19. List<String> dtpNames = DtpRegistry.listAllDtpNames();
  20. // 所有标有DynamicTp注解的线程池
  21. List<String> commonNames = DtpRegistry.listAllCommonNames();
  22. // 检查告警
  23. checkAlarm(dtpNames);
  24. // 指标收集
  25. collect(dtpNames, commonNames);
  26. }
  27. private void collect(List<String> dtpNames, List<String> commonNames) {
  28. // 不收集指标
  29. if (!dtpProperties.isEnabledCollect()) {
  30. return;
  31. }
  32. // 拿到所有的线程池对象,获取到线程池的各种属性统计指标
  33. dtpNames.forEach(x -> {
  34. DtpExecutor executor = DtpRegistry.getDtpExecutor(x);
  35. ThreadPoolStats poolStats = MetricsConverter.convert(executor);
  36. // 指标收集
  37. doCollect(poolStats);
  38. });
  39. commonNames.forEach(x -> {
  40. ExecutorWrapper wrapper = DtpRegistry.getCommonExecutor(x);
  41. // 转换 ThreadPoolStats
  42. ThreadPoolStats poolStats = MetricsConverter.convert(wrapper);
  43. // 指标收集
  44. doCollect(poolStats);
  45. });
  46. // 发送一个CollectEvent事件
  47. publishCollectEvent();
  48. }
  49. /**
  50. * 针对每一个线程池,使用其名称从注册表中获取到线程池对象,然后触发告警
  51. *
  52. * @param dtpNames
  53. */
  54. private void checkAlarm(List<String> dtpNames) {
  55. dtpNames.forEach(x -> {
  56. DtpExecutor executor = DtpRegistry.getDtpExecutor(x);
  57. AlarmManager.doAlarmAsync(executor, SCHEDULE_NOTIFY_ITEMS);
  58. });
  59. // 发送告警AlarmCheckEvent事件
  60. publishAlarmCheckEvent();
  61. }
  62. private void doCollect(ThreadPoolStats threadPoolStats) {
  63. try {
  64. CollectorHandler.getInstance().collect(threadPoolStats, dtpProperties.getCollectorTypes());
  65. } catch (Exception e) {
  66. log.error("DynamicTp monitor, metrics collect error.", e);
  67. }
  68. }
  69. private void publishCollectEvent() {
  70. CollectEvent event = new CollectEvent(this, dtpProperties);
  71. ApplicationContextHolder.publishEvent(event);
  72. }
  73. private void publishAlarmCheckEvent() {
  74. AlarmCheckEvent event = new AlarmCheckEvent(this, dtpProperties);
  75. ApplicationContextHolder.publishEvent(event);
  76. }
  77. @Override
  78. public int getOrder() {
  79. return Ordered.HIGHEST_PRECEDENCE + 2;
  80. }
  81. }

代码比较易懂,这里就不在叙述了。

三、总结

dynamic-tp设计巧妙,代码中设计模式先行,结构清晰易懂,代码规整,同时提供了很多扩展点,通过利用了

  1. Spring

的扩展,和

  1. JUC

原生线程池优势,功能强大。

参考文章

  • dynamic-tp官网
  • 手写精简版动态线程池
  • 基于Nacos的简单动态化线程池实现
  • Nacos配置中心实现一个动态线程池

本文转载自: https://blog.csdn.net/Rookie_CEO/article/details/140886608
版权归原作者 -无-为- 所有, 如有侵权,请联系我们删除。

“科普文:微服务之SpringBoot性能优化器动态线程池【Dynamic-Tp】特性和源码解读”的评论:

还没有评论