@EnableConfigurationProperties(XXXXElasticSearchProperties.class)
@ConditionalOnProperty(value = "xxxxx.es.enabled", havingValue = "true")
@ConditionalOnClass(RestHighLevelClient.class)
@ConditionalOnBean(RestHighLevelClient.class)
public class LogAutoConfig {
@Bean(name = "restHighLevelClient")
public RestHighLevelClient restHighLevelClient() {
// 拆分地址
YidianElasticSearchProperties.Rest rest = yidianElasticSearchProperties.getRest();
final boolean credentials =
rest == null || StringUtils.isEmpty(rest.getPassword()) || StringUtils.isEmpty(rest.getUsername());
// 权限验证
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
if (!credentials) {
// 配置权限验证
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(rest.getUsername(), rest.getPassword()));
}
// 转换成 HttpHost 数组
HttpHost[] httpHost =
yidianElasticSearchProperties.getUris().stream().map(HttpHost::create).toArray(HttpHost[]::new);
// 构建连接对象
RestClientBuilder builder = RestClient.builder( httpHost);
// 异步连接延时配置
builder.setRequestConfigCallback(requestConfigBuilder -> {
requestConfigBuilder.setConnectTimeout(yidianElasticSearchProperties.getConnectTimeout());
requestConfigBuilder.setSocketTimeout(yidianElasticSearchProperties.getSocketTimeout());
requestConfigBuilder
.setConnectionRequestTimeout(yidianElasticSearchProperties.getConnectionRequestTimeout());
return requestConfigBuilder;
});
// 异步连接数配置
builder.setHttpClientConfigCallback( httpClientBuilder -> {
httpClientBuilder.setMaxConnTotal(yidianElasticSearchProperties.getMaxConnectNum());
httpClientBuilder.setMaxConnPerRoute(yidianElasticSearchProperties.getMaxConnectPerRoute());
if (credentials) {
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
return httpClientBuilder;
});
return new RestHighLevelClient(builder);
}
}
这个配置在自定义的 starer
里面,启动时这个类有被扫描到但是不符合 math
所以没有被装配。
然后我手动复制一份这个类命名为 LogAutoConfig1
,并删除了 @ConditionalOnClass
@ConditionalOnBean
等一系列条件装配注解,神奇的是这个它居然报错 restHighLevelClient define in starter xxx path
说是在 starter 中 define 了,这就很奇怪了之前不是都没有装配,这下为什么会提示 define
了,于是我删除了 LogAutoConfig1
中的 restHighLevelClient
这部分代码,至此代码成功注册到 spring
。
这是为什么?
1
wolfie 2022-07-22 18:27:43 +08:00
@ConditionalOnBean(RestHighLevelClient.class)
确定不是 OnMissing ? |
2
cnit OP @wolfie 就是 @ConditionalOnBean(RestHighLevelClient.class) 这块是离职的同事写的公用模块,其他项目里面都是好的
|
3
cnit OP 已解决 另外一个 starter 里面注册了 RestHighLevelClient ,引入另外一个 starter 就好了,从而解释了 @ConditionalOnBean(RestHighLevelClient.class) 但是这个注解从逻辑上来讲还是有些问题
|
4
wolfie 2022-07-25 09:29:34 +08:00
建议先看看 ConditionalOnBean 相关文档。
|
5
slomo 2022-07-26 17:58:28 +08:00
有了一个 RestHighLevelClient 再注册一个 RestHighLevelClient... 没搞这是什么逻辑
|
6
cnit OP |