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完成相关功能的开发。

相关推荐
m51274 分钟前
LinuxC语言
java·服务器·前端
IU宝9 分钟前
C/C++内存管理
java·c语言·c++
瓜牛_gn9 分钟前
依赖注入注解
java·后端·spring
熙曦Sakura9 分钟前
完全竞争市场
笔记
hakesashou10 分钟前
Python中常用的函数介绍
java·网络·python
佚先森19 分钟前
2024ARM网络验证 支持一键云注入引流弹窗注册机 一键脱壳APP加固搭建程序源码及教程
java·html
古月居GYH33 分钟前
在C++上实现反射用法
java·开发语言·c++
dr李四维1 小时前
iOS构建版本以及Hbuilder打iOS的ipa包全流程
前端·笔记·ios·产品运营·产品经理·xcode