2. 开始编写动态线程池配置 (dtp-spring-boot-starter模块)
- 创建动态线程池对象
```package com.laoyang.dtp;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
- @author:Kevin
- @create: 2023-10-24 17:13
- @Description: 实现动态线程池对象
*/
public class DtpExecutor extends ThreadPoolExecutor {
public DtpExecutor(int corePoolSize, int maximumPoolSize) {
super(corePoolSize, maximumPoolSize, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));
}
}
创建动态线程池核心配置类
1.相关Bean的注入 2. nacos监听的bean注入
```package com.laoyang.dtp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
/**
* @author:Kevin
* @create: 2023-10-24 18:36
* @Description: 动态线程池核心配置类
*/
@Configuration
public class DtpExecutorAutoConfiguration {
@Autowired
private Environment environment;
//最大核心数
private static final String CORE_POOL_SIZE = "dtp.core-pool-size";
//最大线程数
private static final String MAXIMUM_POOL_SIZE = "dtp.maximum-pool-size";
//创建动态线程池对象
@Bean
public DtpExecutor executor(){
Integer corePoolSize = Integer.valueOf(environment.getProperty(CORE_POOL_SIZE));
Integer maximumPoolSize = Integer.valueOf(environment.getProperty(MAXIMUM_POOL_SIZE));
return new DtpExecutor(corePoolSize,maximumPoolSize);
}
@Bean
public NacosLinsenter NacosLinsenter(){
return new NacosLinsenter();
}
}
然后通过springboot的自动配置实现将核心配置类注入
创建nacos的监听类并实现动态绑定
通过nacos的 Listener 接口实现相应的方法编写动态变换逻辑,同时实现spring提供的
InitializingBean接口将当前监听类通过nacos的ConfigService的addListener()方法与dataId一一绑定。(只要dataId的配置文件发生改变,当前绑定的监听类就会调用相应的方法),最终注入线程池对象Bean,将修改的配置文件值再注入进线程池对象Bean,就实现动态线程池。