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

相关推荐
XiaoLeisj2 小时前
【JavaEE初阶 — 多线程】单例模式 & 指令重排序问题
java·开发语言·java-ee
paopaokaka_luck2 小时前
【360】基于springboot的志愿服务管理系统
java·spring boot·后端·spring·毕业设计
dayouziei2 小时前
java的类加载机制的学习
java·学习
Yaml44 小时前
Spring Boot 与 Vue 共筑二手书籍交易卓越平台
java·spring boot·后端·mysql·spring·vue·二手书籍
小小小妮子~4 小时前
Spring Boot详解:从入门到精通
java·spring boot·后端
hong1616884 小时前
Spring Boot中实现多数据源连接和切换的方案
java·spring boot·后端
aloha_7894 小时前
从零记录搭建一个干净的mybatis环境
java·笔记·spring·spring cloud·maven·mybatis·springboot
记录成长java5 小时前
ServletContext,Cookie,HttpSession的使用
java·开发语言·servlet
睡觉谁叫~~~5 小时前
一文解秘Rust如何与Java互操作
java·开发语言·后端·rust
dsywws5 小时前
Linux学习笔记之vim入门
linux·笔记·学习