ElasticSearch8.10.2接入SpringBoot3.+

pom.xml文件引入依赖

		<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-client -->
		<dependency>
			<groupId>co.elastic.clients</groupId>
			<artifactId>elasticsearch-java</artifactId>
			<version>8.10.2</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>

 

application.yml文件设置ElasticSearch集群的uri

# ElasticSearch集群的uri
spring:
  elasticsearch:
    uris: http://<服务器ip>:9200

 

配置类往IOC注入Bean

/**
 * Java Client: 8.10
 * <a href="https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/connecting.html">api reference</a>
 */
@Configuration
@RequiredArgsConstructor
public class Conf {

    private final ElasticsearchProperties elasticsearchProperties;

    // 使用原子类
    private final AtomicInteger currentIndex = new AtomicInteger(0);

    /**
     * Create the low-level client
     */
    @Bean
    public RestClient restClient() {
        List<String> uris = elasticsearchProperties.getUris();
        if (ObjectUtils.isEmpty(uris)) {
            throw new ElasticsearchUriException("Elasticsearch URI is not configured.");
        }
        return RestClient
                .builder(HttpHost.create(getNextUri(uris)))
                /*
                    TODO 身份验证标头,设置具有特定请求头时,才能成功访问ElasticSearch
                    .setDefaultHeaders(new Header[]{
                        new BasicHeader("Authorization", "ApiKey " + apiKey)
                    })
                 */
                .setDefaultHeaders(new Header[]{})
                .build();
    }

    /**
     * Create the transport with a Jackson mapper
     */
    @Bean
    public ElasticsearchTransport transport() {
        return new RestClientTransport(
                restClient(), new JacksonJsonpMapper());
    }

    /**
     * And create the API client
     * Synchronous blocking client 同步阻塞式client
     */
    @Bean
    public ElasticsearchClient syncClient() {
        return new ElasticsearchClient(transport());
    }

    /**
     * Asynchronous non-blocking client 异步非阻塞式client
     */
    @Bean
    public ElasticsearchAsyncClient asyncClient() {
        return new ElasticsearchAsyncClient(transport());
    }

    // 获取下一个 URI,使用轮询算法
    private String getNextUri(List<String> uris) {
        // 单机
        if (uris.size() == 1) {
            return uris.get(0);
        }
        // 集群
        synchronized (this) {
            int index = currentIndex.getAndIncrement();
            if (index >= uris.size()) {
                index = 0;
                currentIndex.set(index);
            }
            return uris.get(index);
        }
    }

}

 

配置完成,在你需要操作ElasticSearch的类中注入交给IOC管理的Bean:ElasticsearchClient(同步阻塞式client)、ElasticsearchAsyncClient(异步非阻塞式client)

    @Resource
    private ElasticsearchClient elasticsearchClient;

    /**
     * 索引
     */
    @Test
    @SuppressWarnings("all")
    void index() {
        Assertions.assertDoesNotThrow(() -> {
            // 创建索引products
            elasticsearchClient.indices().create(c -> c.index("products"));
            // 查询索引
//            GetIndexResponse response = elasticsearchClient.indices().get(builder -> builder.index("products"));
//            Map<String, IndexState> result = response.result();
//            System.out.println(result);
            // 判断users索引是否存在文档ID为001的文档
//            BooleanResponse exists = elasticsearchClient.exists(builder -> builder.index("users").id("001"));
//            if (exists.value())
//                log.info("yes, it has.");
            // 删除索引
//            DeleteIndexResponse deleteResponse = elasticsearchClient.indices().delete(builder -> builder.index("women"));
//            boolean acknowledged = deleteResponse.acknowledged();
//            log.info(String.valueOf(acknowledged));
        });
    }

 

关于对文档的操作就自己熟悉API了

参考

posted @ 2023-10-06 23:44  Ashe|||^_^  阅读(156)  评论(0编辑  收藏  举报