ElasticSearch学习笔记-SpringBoot整合Elasticsearch7

项目最近需要接入Elasticsearch7,顺带记录下笔记。
  • Elasticsearch依赖包版本
java 复制代码
<properties>
    <elasticsearch.version>7.9.3</elasticsearch.version>
    <elasticsearch.rest.version>7.9.3</elasticsearch.rest.version>
</properties>

<!-- Elasticsearch依赖包-->
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>${elasticsearch.version}</version>
</dependency>

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>transport</artifactId>
    <version>${elasticsearch.version}</version>
</dependency>

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-client</artifactId>
    <version>${elasticsearch.rest.version}</version>
</dependency>

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>${elasticsearch.rest.version}</version>
</dependency>
  • Elasticsearch连接属性配置,支持单个集群和多个集群的接入。
java 复制代码
@Data
@ConfigurationProperties(prefix = "elasticsearch")
public class ElasticsearchProperties {

    private String clusterName = null;

    private String[] clusterNodes = null;

    private int connectTimeout = 1000;

    private int socketTimeout = 30000;

    private int connectionRequestTimeout = 500;

    private int maxConnectTotal = 100;

    private int maxConnectPerRoute = 100;

}
java 复制代码
@Data
@ConfigurationProperties(prefix = "elasticsearch.multi-cluster")
public class MultiElasticsearchProperties {

    /** 是否开启 **/
    private Boolean enable = false;

    /** 配置 */
    private Map<String, ElasticsearchProperties> configs;

}
  • SpringBoot整合Elasticsearch注入容器自动配置
    注:Elasticsearch7.15之后官方将高级客户端RestHighLevelClient标记为弃用状态。
    单集群实例注入Spring容器。
java 复制代码
@EnableConfigurationProperties({ ElasticsearchProperties.class, MultiElasticsearchProperties.class })
@Import({ ElasticsearchBeanDefinitionRegistrar.class })
@Configuration
public class ElasticsearchAutoConfiguration {
	
	@Bean
	public RestHighLevelClient restHighLevelClient(ElasticsearchProperties elasticsearchProperties) {
		return new RestHighLevelClient((RestClientBuilder)
			Objects.requireNonNull(new RestClientBuilderFactoryBean(elasticsearchProperties).getObject()));
	}

	@Bean
	@ConditionalOnMissingBean
	public ElasticsearchService elasticsearchService(RestHighLevelClient restHighLevelClient) {
		return new ElasticsearchServiceImpl(restHighLevelClient);
	}
	
}

多集群实例注入Spring容器。

java 复制代码
public class ElasticsearchBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware {

    private MultiElasticsearchProperties multiElasticsearchProperties;

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        if (null == multiElasticsearchProperties) {
            return;
        }
        Boolean enable = multiElasticsearchProperties.getEnable();
        if (null == enable || !enable) {
            return;
        }
        Map<String, ElasticsearchProperties> configs = multiElasticsearchProperties.getConfigs();
        if (null == configs || configs.isEmpty()) {
            return;
        }
        configs.forEach((name, elasticsearchProperties) -> {
            RootBeanDefinition beanDefinition = new RootBeanDefinition();
            beanDefinition.setBeanClass(RestHighLevelClient.class);
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(
                Objects.requireNonNull(new RestClientBuilderFactoryBean(elasticsearchProperties).getObject()));
            beanDefinitionRegistry.registerBeanDefinition(String.format("%sRestHighLevelClient", name), beanDefinition);

        });
    }

    @Override
    public void setEnvironment(Environment environment) {
        BindResult<MultiElasticsearchProperties> bindResult = Binder.get(environment)
            .bind(getPropertiesPrefix(MultiElasticsearchProperties.class), MultiElasticsearchProperties.class);
        if (null != bindResult && bindResult.isBound()) {
            multiElasticsearchProperties = bindResult.get();
        }
    }

    private String getPropertiesPrefix(Class<?> clazz) {
        return Objects.requireNonNull(AnnotationUtils.getAnnotation(clazz, ConfigurationProperties.class)).prefix();
    }

}
  • spring.factories文件开启自动配置
java 复制代码
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
   com.component.sdk.elasticsearch7.config.ElasticsearchAutoConfiguration
  • 项目配置文件引入Elasticsearch示例
java 复制代码
elasticsearch:
  cluster-name: cluster
  cluster-nodes:
    - 192.168.0.1:9200
  connect-timeout: 1000
  socket-timeout: 30000
  connection-request-timeout: 500
  max-connect-total: 100
  max-connect-per-route: 100
  multi-cluster:
    enable: false
    configs:
      tmp1:
        cluster-name: cluster
        cluster-nodes:
          - 192.168.0.1:9200
        connect-timeout: 1000
        socket-timeout: 30000
        connection-request-timeout: 500
        max-connect-total: 100
        max-connect-per-route: 100

自此项目可以正常连接Elasticsearch完成相关功能的开发。

相关推荐
mghio37 分钟前
Dubbo 中的集群容错
java·微服务·dubbo
咖啡教室5 小时前
java日常开发笔记和开发问题记录
java
咖啡教室6 小时前
java练习项目记录笔记
java
鱼樱前端6 小时前
maven的基础安装和使用--mac/window版本
java·后端
RainbowSea7 小时前
6. RabbitMQ 死信队列的详细操作编写
java·消息队列·rabbitmq
RainbowSea7 小时前
5. RabbitMQ 消息队列中 Exchanges(交换机) 的详细说明
java·消息队列·rabbitmq
李少兄8 小时前
Unirest:优雅的Java HTTP客户端库
java·开发语言·http
此木|西贝9 小时前
【设计模式】原型模式
java·设计模式·原型模式
可乐加.糖9 小时前
一篇关于Netty相关的梳理总结
java·后端·网络协议·netty·信息与通信