1.引入maven依赖
 		<dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>jakarta.json</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>co.elastic.clients</groupId>
            <artifactId>elasticsearch-java</artifactId>
            <version>8.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>8.4.1</version>
        </dependency>
2.application.yml添加配置
spring:
  elasticsearch:
    rest:
      uris: 127.0.0.1:9200 #es
      username: elastic
      password: ******
3.编写config文件
package com.example.demo.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

@Configuration
public class ElasticSearchConfig {

    @Value("${spring.elasticsearch.rest.uris}")
    private String hosts;

    @Value("${spring.elasticsearch.rest.username}")
    private String userName;

    @Value("${spring.elasticsearch.rest.password}")
    private String passWord;


    @Bean
    public ElasticsearchClient elasticsearchClient(){
        HttpHost[] httpHosts = toHttpHost();
        // 无验证信息
        //RestClient restClient = RestClient.builder(httpHosts).build();

        // 有验证信息
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(
                AuthScope.ANY, new UsernamePasswordCredentials(userName, passWord));

        RestClientBuilder builder = RestClient.builder(httpHosts);
        builder.setRequestConfigCallback(
                new RestClientBuilder.RequestConfigCallback() {
                    @Override
                    public RequestConfig.Builder customizeRequestConfig(
                            RequestConfig.Builder requestConfigBuilder) {
                        return requestConfigBuilder.setSocketTimeout(60000).setConnectTimeout(5000);
                    }
                });
        builder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {

                        return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                });
        RestClient restClient = builder.build();
        // Create the transport with a Jackson mapper
        ElasticsearchTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
        // And create the API client
        return new ElasticsearchClient(transport);
    }

    private HttpHost[] toHttpHost() {
        if (!StringUtils.hasLength(hosts)) {
            throw new RuntimeException("invalid elasticsearch configuration. elasticsearch.hosts不能为空!");
        }

        // 多个IP逗号隔开
        String[] hostArray = hosts.split(",");
        HttpHost[] httpHosts = new HttpHost[hostArray.length];
        HttpHost httpHost;
        for (int i = 0; i < hostArray.length; i++) {
            String[] strings = hostArray[i].split(":");
            httpHost = new HttpHost(strings[0], Integer.parseInt(strings[1]), "http");
            httpHosts[i] = httpHost;
        }

        return httpHosts;
    }

}

启动demo项目,通过控制台日志查看是否能够正常连接es。

4.在DemoApplicationTests编写简单测试操作es。
@SpringBootTest
@Slf4j
class DemoApplicationTests {

    @Autowired
    private ElasticsearchClient client;

    @Test
    public void createTest() throws IOException {
        log.info("创建索引");
        //写法比RestHighLevelClient更加简洁
        CreateIndexResponse indexResponse = client.indices().create(c -> c.index("user"));
        log.info(String.valueOf(indexResponse));
    }

    @Test
    public void getCompanyList() throws IOException {
 		log.info("查询索引");	
        GetIndexResponse getIndexResponse = client.indices().get(i -> i.index("user"));
        log.info(String.valueOf(getIndexResponse));
    }

    @Test
    public void existsTest() throws IOException {
        log.info("测试index是否存在");
        BooleanResponse booleanResponse = client.indices().exists(e -> e.index("user"));
        log.info(String.valueOf(booleanResponse.value()));
    }

    @Test
    public void userInsert() throws IOException {
        log.info("user信息插入");
        //创建user列表
        List<User> users = new ArrayList<>();
        User user = new User();
        user.setId("18");
        user.setName("李三");
        user.setAge(13);
        user.setSex("男");
        users.add(user);
        
        List<BulkOperation> bulkOperations = new ArrayList<>();
        //将user中id作为es id,也可不指定id es会自动生成id
        users.forEach(a -> bulkOperations.add(BulkOperation.of(b -> b.index(c -> c.id(a.getId()).document(a)))));
        client.bulk(x ->x.index("user").operations(bulkOperations));

    }

}
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐