欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

elastic stack(六) springboot整合es

程序员文章站 2024-01-19 19:16:04
...

elasticsearch版本类型统一7.8.0

1、项目架构如下

elastic stack(六) springboot整合es

2、配置文件(进行验证登陆的时候需要输入账号、密码)

/**
 * @author yfc
 * @date 2020/8/17
 * @description elasticsearch配置文件
 * @parmas
 */
@Configuration
public class ElasticsearchClientConfig {

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        //集群构建多个,非集群构建一个 RestClient.builder(
        //                        new HttpHost("localhost", 9200, "http"),
        //                        new HttpHost("localhost", 9201, "http")))
        //1、用户认证对象
        final CredentialsProvider credentialsProvider=new BasicCredentialsProvider();
        //2、设置账号密码
        credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("elastic","elastic"));
        //3、创建rest对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("121.0.0.170", 9200, "http")).setHttpClientConfigCallback(
                        new RestClientBuilder.HttpClientConfigCallback() {
                            @Override
                            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
                                return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                            }
                        }
                ));
        return client;
    }


}

没有设置账号密码的配置文件如下:

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        //集群构建多个,非集群构建一个 RestClient.builder(
        //                        new HttpHost("localhost", 9200, "http"),
        //                        new HttpHost("localhost", 9201, "http")))
        //创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("121.0.0.170", 9200, "http")));
        return client;
    }

3、测试类

@SpringBootTest
class DemoApplicationTests {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * @Author yfc
     * @Date 2020/8/17
     * @Despration 测试索引的创建
     * @Param
     */
    @Test
    void testCreateIndex() throws IOException {
        //1、创建索引请求
        CreateIndexRequest request=new CreateIndexRequest("yfc");
        //2、执行请求 IndicesClient
        CreateIndexResponse createIndexResponse=restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse);
    }

}

4、创建索引成功

elastic stack(六) springboot整合es

相关标签: elastic stack