ElasticSearch学习笔记-SpringBoot整合Elasticsearch7

项目最近需要接入Elasticsearch7,顺带记录下笔记。
  • Elasticsearch依赖包版本
<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连接属性配置,支持单个集群和多个集群的接入。
@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;

}
@Data
@ConfigurationProperties(prefix = "elasticsearch.multi-cluster")
public class MultiElasticsearchProperties {

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

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

}
  • SpringBoot整合Elasticsearch注入容器自动配置
    注:Elasticsearch7.15之后官方将高级客户端RestHighLevelClient标记为弃用状态。
    单集群实例注入Spring容器。
@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容器。

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文件开启自动配置
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
   com.component.sdk.elasticsearch7.config.ElasticsearchAutoConfiguration
  • 项目配置文件引入Elasticsearch示例
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完成相关功能的开发。

你可能感兴趣的:(J2EE,ElasticSearch,elasticsearch,java,spring,boot,笔记)