SpringBoot整合ElasticSearch

ElasticSearch-Rest-Client

1、9300:Tcp

  • spring-data-elasticsearch:transport-api.jar;
    • springboot版本不同,transport-api不同,不能适配不同的es版本;
    • 7.x不建议使用,8以后废弃
      2、9200:Http
  • JestClient:非官方,更新慢;
  • RestTemplate:模拟发送Http请求,Es很多操作需要自己封装,麻烦;
  • HttpClient:同上;
  • ElasticSearch-Rest-Client:官方RestClient,封装了很多ES操作,API层次分明,上手简单;

Springboot集成ElasticSearch

1、引入依赖(版本最好与ES版本一直)

        
        <dependency>
            <groupId>org.elasticsearch.clientgroupId>
            <artifactId>elasticsearch-rest-high-level-clientartifactId>
            <version>7.4.2version>
        dependency>

2、编写配置类(主要是获取RestHighLevelClient)

/**
 * 1、导入依赖
 * 2、编写配置,给容器中注入RestHighLevelClient对象
 * 3、操作Es
 */
@Configuration
public class GulimallElasticSearchConfig {

    public static final RequestOptions COMMON_OPTIONS;

    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
//        builder.addHeader("Authorization","Bearer" + TOKEN);
//        builder.setHttpAsyncResponseConsumerFactory(
//                new HttpAsyncResponseConsumerFactory.
//                        HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024)
//        );
        COMMON_OPTIONS = builder.build();
    }

    @Bean
    public RestHighLevelClient esRestClient() {

        RestClientBuilder builder = null;

        builder = RestClient.builder(new HttpHost("192.168.37.129", 9200, "http"));

        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(builder);
        return restHighLevelClient;
    }

}

这样即可在其他地方使用RestHighLevelClient 对象;

测试类中进行测试

@RunWith(SpringRunner.class)
@SpringBootTest
class GulimallSearchApplicationTests {


    @Resource
    RestHighLevelClient restHighLevelClient;

	//向对应的index中写入数据
    @Test
    public void indexData() throws IOException {
        //初始化请求,构造函数中指定index名
        IndexRequest indexRequest = new IndexRequest("users");
        //设置id
        indexRequest.id("2");
/*        indexRequest.source("userName", "zhangsan");
        indexRequest.source("age", 18);*/
        User user = new User("zhangsan", "male", 18);
        String jsonString = JSON.toJSONString(user);
        //要保存的内容
        indexRequest.source(jsonString, XContentType.JSON);
        //执行操作
        IndexResponse index = restHighLevelClient.index(indexRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

        //提取有用的响应数据
        System.out.println(index);
    }

    @NoArgsConstructor
    @AllArgsConstructor
    @Data
    class User{
        private String userName;
        private String gender;
        private Integer age;


    }

    @Test
    void contextLoads() {
        System.out.println(restHighLevelClient);
    }

}

你可能感兴趣的:(ElasticSearch,java,elasticsearch,nosql,flink)