目錄
- 回顧昨日
- nacos集成
- Spring Cloud Alibaba 方式
- Nacos Spring Boot 方式
- Apollo集成
- 自研配置中心對(duì)接
- 無配置中心對(duì)接
- 實(shí)現(xiàn)源碼分析
- 兼容Apollo和Nacos NoClassDefFoundError
- Apollo自動(dòng)刷新問題
回顧昨日
上篇文章 《一時(shí)技癢,擼了個(gè)動(dòng)態(tài)線程池,源碼放Github了》(https://mp.weixin.qq.com/s/JM9idgFPZGkRAdCpw0NaKw)發(fā)出后很多讀者私下問我這個(gè)能不能用到工作中,用肯定是可以用的,本身來說是對(duì)線程池的擴(kuò)展,然后對(duì)接了配置中心和監(jiān)控。
目前用的話主要存在下面幾個(gè)問題:
- 還沒發(fā)布到Maven中央倉(cāng)庫(kù)(后續(xù)會(huì)做),可以自己編譯打包發(fā)布到私有倉(cāng)庫(kù)(臨時(shí)方案)
- 耦合了Nacos,如果你項(xiàng)目中沒有用Nacos或者用的其他的配置中心怎么辦?(本文內(nèi)容)
- 只能替換業(yè)務(wù)線程池,像一些框架中的線程池?zé)o法替換(構(gòu)思中)
本文的重點(diǎn)就是介紹如何對(duì)接Nacos 和 Apollo,因?yàn)橐婚_始就支持了Nacos,但是支持的方式是依賴了Spring Cloud Alibaba ,如果是沒有用Spring Cloud Alibaba 如何支持,也是需要擴(kuò)展的。
Nacos集成
Nacos集成的話分兩種方式,一種是你的項(xiàng)目使用了Spring Cloud Alibaba ,另一種是只用了Spring Boot 方式的集成。
Spring Cloud Alibaba方式
加入依賴:
<dependency>
<groupId>com.cxytiandi</groupId>
<artifactId>kitty-spring-cloud-starter-dynamic-thread-pool</artifactId>
</dependency>
然后在Nacos中增加線程池的配置,比如:
kitty.threadpools.executors[0].threadPoolName=TestThreadPoolExecutor
kitty.threadpools.executors[0].corePoolSize=4
kitty.threadpools.executors[0].maximumPoolSize=4
kitty.threadpools.executors[0].queueCapacity=5
kitty.threadpools.executors[0].queueCapacityThreshold=22
然后在項(xiàng)目中的bootstrap.properties中配置要使用的Nacos data-id。
spring.cloud.nacos.config.ext-config[0].data-id=kitty-cloud-thread-pool.properties
spring.cloud.nacos.config.ext-config[0].group=BIZ_GROUP
spring.cloud.nacos.config.ext-config[0].refresh=true
Nacos Spring Boot方式
如果你的項(xiàng)目只是用了Nacos的Spring Boot Starter,比如下面:
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
</dependency>
那么集成的步驟跟Spring Cloud Alibaba方式一樣,唯一不同的就是配置的加載方式。使用@NacosPropertySource進(jìn)行加載。
@NacosPropertySource(dataId = NacosConstant.HREAD_POOL, groupId = NacosConstant.BIZ_GROUP, autoRefreshed = true, type = ConfigType.PROPERTIES)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
然后需要在bootstrap.properties中關(guān)閉Spring Cloud Alibaba Nacos Config的自動(dòng)配置。
spring.cloud.nacos.config.enabled=false
Apollo集成
Apollo的使用我們都是用它的client,依賴如下:
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId>
<version>1.4.0</version>
</dependency>
集成Thread-Pool還是老的步驟,先添加Maven依賴:
<dependency>
<groupId>com.cxytiandi</groupId>
<artifactId>kitty-spring-cloud-starter-dynamic-thread-pool</artifactId>
</dependency>
然后配置線程池配置的namespace:
apollo.bootstrap.namespaces=thread-pool-config
Properties不用加后綴,如果是yaml文件那么需要加上后綴:
apollo.bootstrap.namespaces=thread-pool-config.yaml
如果你項(xiàng)目中用到了多個(gè)namespace的話,需要在線程池的namespace中指定,主要是監(jiān)聽配置修改需要用到。
kitty.threadpools.apolloNamespace=thread-pool-config.yaml
自研配置中心對(duì)接
如果你們項(xiàng)目使用的是自研的配置中心那該怎么使用動(dòng)態(tài)線程池呢?
最好的方式是跟Nacos一樣,將配置跟Spring進(jìn)行集成,封裝成PropertySource。
Apollo中集成Spring代碼參考:https://github.com/ctripcorp/apollo/blob/master/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/PropertySourcesProcessor.java
因?yàn)榕渲妙愂怯玫腀ConfigurationProperties,這樣就相當(dāng)于無縫集成了。
如果沒和Spring進(jìn)行集成,那也是有辦法的,可以在項(xiàng)目啟動(dòng)后獲取你們的配置,然后修改
DynamicThreadPoolProperties配置類,再初始化線程池即可,具體步驟跟下面的無配置中心對(duì)接一致。DynamicThreadPoolManager提供了createThreadPoolExecutor()來創(chuàng)建線程池。
無配置中心對(duì)接
如果你的項(xiàng)目中沒有使用配置中心怎么辦?還是可以照樣使用動(dòng)態(tài)線程池的。
直接將線程池的配置信息放在項(xiàng)目的application配置文件中即可,但是這樣的缺點(diǎn)就是無法動(dòng)態(tài)修改配置信息了。
如果想有動(dòng)態(tài)修改配置的能力,可以稍微擴(kuò)展下,這邊我提供下思路。
編寫一個(gè)Rest API,參數(shù)就是整個(gè)線程池配置的內(nèi)容,可以是Properties文件也可以是Yaml文件格式。
這個(gè)API的邏輯就是注入我們的DynamicThreadPoolProperties,調(diào)用refresh()刷新Properties文件,調(diào)用refreshYaml()刷新Yaml文件。
然后注入DynamicThreadPoolManager,調(diào)用refreshThreadPoolExecutor()刷新線程池參數(shù)。
實(shí)現(xiàn)源碼分析
首先,我們要實(shí)現(xiàn)的需求是同時(shí)適配Nacos和Apollo兩個(gè)主流的配置中心,一般有兩種做法。
第一種:將跟Nacos和Apollo相關(guān)的代碼獨(dú)立成一個(gè)模塊,使用者按需引入。
第二種:還是一個(gè)項(xiàng)目,內(nèi)部做兼容。
我這邊采取的是第二種,因?yàn)榇a量不多,沒必要拆分成兩個(gè)。
需要在pom中同時(shí)增加兩個(gè)配置中心的依賴,需要設(shè)置成可選(optional=true)。
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-nacos-config</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId>
<version>1.4.0</version>
<optional>true</optional>
</dependency>
然后內(nèi)部將監(jiān)聽配置動(dòng)態(tài)調(diào)整線程池參數(shù)的邏輯分開,ApolloConfigUpdateListener和NacosConfigUpdateListener。
在自動(dòng)裝配Bean的時(shí)候按需裝配對(duì)應(yīng)的Listener。
@ImportAutoConfiguration(DynamicThreadPoolProperties.class)
@Configuration
public class DynamicThreadPoolAutoConfiguration {
@Bean
@ConditionalOnClass(value = com.alibaba.nacos.api.config.ConfigService.class)
public NacosConfigUpdateListener nacosConfigUpdateListener() {
return new NacosConfigUpdateListener();
}
@Bean
@ConditionalOnClass(value = com.ctrip.framework.apollo.ConfigService.class)
public ApolloConfigUpdateListener apolloConfigUpdateListener() {
return new ApolloConfigUpdateListener();
}
}
兼容Apollo和Nacos NoClassDefFoundError
通過@ConditionalOnClass來判斷當(dāng)前項(xiàng)目中使用的是哪種配置中心,然后裝配對(duì)應(yīng)的Listener。上面的代碼看上去沒問題,在實(shí)際使用的過程去報(bào)了下面的錯(cuò)誤:
Caused by: java.lang.NoClassDefFoundError: Lcom/alibaba/nacos/api/config/ConfigService;
at java.lang.Class.getDeclaredFields0(Native Method) ~[na:1.8.0_40]
at java.lang.Class.privateGetDeclaredFields(Class.java:2583) ~[na:1.8.0_40]
at java.lang.Class.getDeclaredFields(Class.java:1916) ~[na:1.8.0_40]
at org.springframework.util.ReflectionUtils.getDeclaredFields(ReflectionUtils.java:755) ~[spring-core-5.1.8.RELEASE.jar:5.1.8.RELEASE]
... 22 common frames omitted
Caused by: java.lang.ClassNotFoundException: com.alibaba.nacos.api.config.ConfigService
at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_40]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_40]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_40]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_40]
... 26 common frames omitted
比如我的項(xiàng)目是用的Apollo,然后我集成了動(dòng)態(tài)線程池,在啟動(dòng)的時(shí)候就報(bào)上面的錯(cuò)誤了,錯(cuò)誤原因是找不到Nacos相關(guān)的類。
但其實(shí)我已經(jīng)用了@ConditionalOnClass來判斷,這個(gè)是因?yàn)槟愕腄ynamicThreadPoolAutoConfiguration類是生效的,Spring會(huì)去裝載DynamicThreadPoolAutoConfiguration類,DynamicThreadPoolAutoConfiguration中有NacosConfigUpdateListener的實(shí)例化操作,而項(xiàng)目中又沒有依賴Nacos,所以就報(bào)錯(cuò)了。
這種情況我們需要將裝配的邏輯拆分的更細(xì),直接用一個(gè)單獨(dú)的類去配置,將@ConditionalOnClass放在類上。
這里我采用了靜態(tài)內(nèi)部類的方式,如果項(xiàng)目中沒有依賴Nacos,那么NacosConfiguration就不會(huì)生效,也就不會(huì)去初始化NacosConfigUpdateListener。
@Configuration
@ConditionalOnClass(value = com.alibaba.nacos.api.config.ConfigService.class)
protected static class NacosConfiguration {
@Bean
public NacosConfigUpdateListener nacosConfigUpdateListener() {
return new NacosConfigUpdateListener();
}
}
@Configuration
@ConditionalOnClass(value = com.ctrip.framework.apollo.ConfigService.class)
protected static class ApolloConfiguration {
@Bean
public ApolloConfigUpdateListener apolloConfigUpdateListener() {
return new ApolloConfigUpdateListener();
}
}
這個(gè)地方我順便提一個(gè)點(diǎn),就是為什么我們平時(shí)要多去看看開源框架的源碼。因?yàn)橄襁@種適配多個(gè)框架的邏輯比較常見,那么一些開源框架中肯定也有類似的邏輯。如果你之前有看過其他的框架是怎么實(shí)現(xiàn)的,那么這里你就會(huì)直接采取那種方式。
比如Spring Cloud OpenFeign中對(duì)Http的客戶端做了多個(gè)框架的適配,你可以用HttpClient也可以用Okhttp,這不就是跟我們這個(gè)一樣的邏輯么。
我們看下源碼就知道了,如下圖:


Apollo自動(dòng)刷新問題
在實(shí)現(xiàn)的過程中還遇到一個(gè)問題也跟大家分享下,就是Apollo中@ConfigurationProperties配置類,在配置信息變更后不會(huì)自動(dòng)刷新,需要配合RefreshScope或者EnvironmentChangeEvent來實(shí)現(xiàn)。
下圖是Apollo文檔的原話:

Nacos刷新是沒問題的,只不過在收到配置變更的消息時(shí),配置信息還沒刷新到Bean里面去,所以再刷新的時(shí)候單獨(dú)起了一個(gè)線程去做,然后在這個(gè)線程中睡眠了1秒鐘(可通過配置調(diào)整)。
如果按照Apollo文檔中給的方式,肯定是可以實(shí)現(xiàn)的。但是不太好,因?yàn)樾枰蕾嘢pring Cloud Context。主要是考慮到使用者并不一定會(huì)用到Spring Cloud,我們的基礎(chǔ)是Spring Boot。
萬一使用者就是在Spring Boot項(xiàng)目中用了Apollo, 然后又用了我的動(dòng)態(tài)線程池,這怎么搞?
最后我采用了手動(dòng)刷新的方式,當(dāng)配置發(fā)生變更的時(shí)候,我會(huì)通過Apollo的客戶端,重新拉取整個(gè)配置文件的內(nèi)容,然后手動(dòng)刷新配置類。
config.addChangeListener(changeEvent -> {
ConfigFileFormat configFileFormat = ConfigFileFormat.Properties;
String getConfigNamespace = finalApolloNamespace;
if (finalApolloNamespace.contains(ConfigFileFormat.YAML.getValue())) {
configFileFormat = ConfigFileFormat.YAML;
// 去除.yaml后綴,getConfigFile時(shí)候會(huì)根據(jù)類型自動(dòng)追加
getConfigNamespace = getConfigNamespace.replaceAll("." + ConfigFileFormat.YAML.getValue(), "");
}
ConfigFile configFile = ConfigService.getConfigFile(getConfigNamespace, configFileFormat);
String content = configFile.getContent();
if (finalApolloNamespace.contains(ConfigFileFormat.YAML.getValue())) {
poolProperties.refreshYaml(content);
} else {
poolProperties.refresh(content);
}
dynamicThreadPoolManager.refreshThreadPoolExecutor(false);
log.info("線程池配置有變化,刷新完成");
});
刷新邏輯:
public void refresh(String content) {
Properties properties = new Properties();
try {
properties.load(new ByteArrayInputStream(content.getBytes()));
} catch (IOException e) {
log.error("轉(zhuǎn)換Properties異常", e);
}
doRefresh(properties);
}
public void refreshYaml(String content) {
YamlPropertiesFactoryBean bean = new YamlPropertiesFactoryBean();
bean.setResources(new ByteArrayResource(content.getBytes()));
Properties properties = bean.getObject();
doRefresh(properties);
}
private void doRefresh(Properties properties) {
Map<String, String> dataMap = new HashMap<String, String>((Map) properties);
ConfigurationPropertySource sources = new MapConfigurationPropertySource(dataMap);
Binder binder = new Binder(sources);
binder.bind("kitty.threadpools", Bindable.ofInstance(this)).get();
}
目前只支持Properties和Yaml文件配置格式。
感興趣的Star下唄:https://github.com/yinjihuan/kitty
關(guān)于作者:尹吉?dú)g,簡(jiǎn)單的技術(shù)愛好者,《Spring Cloud微服務(wù)-全棧技術(shù)與案例解析》, 《Spring Cloud微服務(wù) 入門 實(shí)戰(zhàn)與進(jìn)階》作者, 公眾號(hào) 猿天地 發(fā)起人。個(gè)人微信 jihuan900,歡迎勾搭。