1. 异常
在使用springboot2.2.8+elasticsearch6.8.10时,测试时报错:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'elasticsearchClient' defined in class path resource [org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.elasticsearch.client.transport.TransportClient]: Factory method 'elasticsearchClient' threw exception; nested exception is java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4]
2. 原因
- Elasticsearch 和 Redis 底层都使用到了 Netty , 在项目启动时会冲突。
涉及到的类:NettyRuntime,Netty4Util。
- 查看NettyRuntime类,可以看下源码:
public final class NettyRuntime {
private static final NettyRuntime.AvailableProcessorsHolder holder = new NettyRuntime.AvailableProcessorsHolder();
public static void setAvailableProcessors(int availableProcessors) {
holder.setAvailableProcessors(availableProcessors);
}
public static int availableProcessors() {
return holder.availableProcessors();
}
private NettyRuntime() {
}
static class AvailableProcessorsHolder {
private int avail