springboot整合Elasticsearch(High Level REST Client方式)

注意:spring的elasticsearch会与High Level REST Client会产生冲突


1.引入jar包(pom文件中添加)

<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-high-level-client -->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.10.0</version>
</dependency>

如果你也跟我一样,项目中用的是springboot 2.1.7.RELEASE,那么应该使用6.4.3的elasticsearch-rest-high-level-client,因为会存在版本冲突

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>6.4.3</version>
</dependency>

2.在配置文件(application.yml)中配置

elasticsearch:
  hostname: 127.0.0.1
  port: 9200

3.创建RestClientConfig


import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.apache.http.client.config.RequestConfig;

/**
 * @author 
 * @Date 2020-12-08 15:12
 * @Version 1.0
 * @name es
 */
@Configuration
public class RestClientConfig {

    @Value("${elasticsearch.hostname}")
    private String hostname;

    @Value("${elasticsearch.port}")
    private int port;

    /**
     * LowLevelRestConfig
     *
     * @param
     * @return org.elasticsearch.client.RestClient
     * @author wliduo[i@dolyw.com]
     * @date 2019/8/12 18:56
     */
    @Bean
    public RestClient restClient() {
        // 如果有多个从节点可以持续在内部new多个HttpHost,参数1是IP,参数2是端口,参数3是通信协议
        RestClientBuilder clientBuilder = RestClient.builder(new HttpHost(hostname, port, "http"));
        // 设置Header编码
        Header[] defaultHeaders = {new BasicHeader("content-type", "application/json")};
        clientBuilder.setDefaultHeaders(defaultHeaders);
        // 添加其他配置,这些配置都是可选的,详情配置可看https://blog.csdn.net/jacksonary/article/details/82729556
        return clientBuilder.build();
    }

    /**
     * HighLevelRestConfig
     *
     * @param
     * @return org.elasticsearch.client.RestClient
     * @author wliduo[i@dolyw.com]
     * @date 2019/8/12 18:56
     */
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        // 如果有多个从节点可以持续在内部new多个HttpHost,参数1是IP,参数2是端口,参数3是通信协议
        // 该方法接收一个RequestConfig.Builder对象,对该对象进行修改后然后返回。
        return new RestHighLevelClient(RestClient.builder(new HttpHost(hostname, port, "http"))
                .setRequestConfigCallback(requestConfigBuilder -> {
                    return requestConfigBuilder.setConnectTimeout(5000 * 1000) // 连接超时(默认为1秒)
                            .setSocketTimeout(6000 * 1000);// 套接字超时(默认为30秒)//更改客户端的超时限制默认30秒现在改为100*1000分钟
                }));
    }

}

4.创建接口测试


import com.alibaba.fastjson.JSONObject;
import com.boying.platform.common.utils.ResultUtil;
import com.boying.platform.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.RequestLine;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.*;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author lzy
 * @Date 2020-12-08 15:15
 * @Version 1.0
 * @name ES测试
 */
@Slf4j
@RestController
@RequestMapping("/lowApi")
@CrossOrigin(maxAge = 3600)
public class LowLevelRestController {

    /**
     * PATTERN
     */
    private static Pattern PATTERN = Pattern.compile("\\s*|\t|\r|\n");

    @Autowired
    private RestClient restClient;

    @GetMapping("/test")
    public Result<Object> test(){
        return new ResultUtil<>().setSuccessMsg("操作成功");
    }

    /**
     * 同步执行HTTP请求
     *
     * @param
     * @return org.springframework.http.ResponseEntity<java.lang.String>
     * @throws IOException
     * @author wliduo[i@dolyw.com]
     * @date 2019/8/8 17:15
     */
    @GetMapping("/es")
    public Result<Object> getEsInfo() throws IOException {
        Request request = new Request("GET", "/");
        // performRequest是同步的,将阻塞调用线程并在请求成功时返回Response,如果失败则抛出异常
        String responseBody = "";
        try {
            Response response = restClient.performRequest(request);
            // 获取请求行
            RequestLine requestLine = response.getRequestLine();
            // 获取host
            HttpHost host = response.getHost();
            // 获取状态码
            int statusCode = response.getStatusLine().getStatusCode();
            // 获取响应头
            Header[] headers = response.getHeaders();
            // 获取响应体
            responseBody = EntityUtils.toString(response.getEntity());
        }catch (Exception e){
            log.error(String.valueOf(e));
            return new ResultUtil<>().setErrorMsg("请求超时");
        }
        return new ResultUtil<>().setData(JSONObject.parseObject(responseBody));
    }


    /**
     * 异步执行HTTP请求
     *
     * @param
     * @return org.springframework.http.ResponseEntity<java.lang.String>
     * @author wliduo[i@dolyw.com]
     * @date 2019/8/8 17:15
     */
    @GetMapping("/es/async")
    public Result<Object> asynchronous() {
        Request request = new Request("GET", "/");
        restClient.performRequestAsync(request, new ResponseListener() {
            @Override
            public void onSuccess(Response response) {
                log.info("异步执行HTTP请求并成功");
                log.info(JSONObject.toJSONString(response));
            }

            @Override
            public void onFailure(Exception exception) {
                log.error("异步执行HTTP请求并失败");
                log.error(JSONObject.toJSONString(exception));
            }
        });
        return new ResultUtil<>().setData(null);
    }

    /**
     * 分词分页查询列表
     *
     * @param page
     * @param rows
     * @param keyword
     * @return com.example.common.ResponseBean
     * @author wliduo[i@dolyw.com]
     * @date 2019/8/9 15:32
     */
    @GetMapping("/book")
    public Result<Object> getBookList(@RequestParam(defaultValue = "1") Integer page,
                                    @RequestParam(defaultValue = "10") Integer rows,
                                    String keyword) {
        Request request = new Request("POST", "/_search");
        // 添加Json返回优化
        request.addParameter("pretty", "true");
        // 拼接查询Json
        IndexRequest indexRequest = new IndexRequest();
        XContentBuilder builder = null;
        Response response = null;
        String responseBody = null;
        try {
            builder = JsonXContent.contentBuilder()
                    .startObject()
                    .startObject("query")
                    .startObject("multi_match")
                    .field("query", keyword)
                    .array("fields", "name", "desc")
                    .endObject()
                    .endObject()
                    .startObject("sort")
                    .startObject("id")
                    .field("order", "desc")
                    .endObject()
                    .endObject()
                    .endObject();
            indexRequest.source(builder);
            // 设置请求体并指定ContentType,如果不指定会乱码
            request.setEntity(new NStringEntity(indexRequest.source().utf8ToString(), ContentType.APPLICATION_JSON));
            // 执行HTTP请求
            response = restClient.performRequest(request);
            responseBody = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            return new ResultUtil<>().setData(null);
        }
        return new ResultUtil<>().setData(JSONObject.parseObject(responseBody));
    }

    /**
     * 根据Id获取ES对象
     *
     * @param id
     * @return org.springframework.http.ResponseEntity<java.lang.String>
     * @author wliduo[i@dolyw.com]
     * @date 2019/8/8 17:48
     */
    @GetMapping("/book/{id}")
    public Result<Object> getBookById(@PathVariable("id") String id) {
        Request request = new Request("GET", "/book/book/" +
                id);
        // 添加Json返回优化
        request.addParameter("pretty", "true");
        Response response = null;
        String responseBody = null;
        try {
            // 执行HTTP请求
            response = restClient.performRequest(request);
            responseBody = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            return new ResultUtil<>().setErrorMsg("");
        }
        return new ResultUtil<>().setData(JSONObject.parseObject(responseBody));
    }

    /**
     * 添加ES对象, Book的ID就是ES中存储的Document的ID,ES的POST和PUT可以看下面这个文章
     * https://blog.csdn.net/z457181562/article/details/93470152
     *
     * @param
     * @return org.springframework.http.ResponseEntity<java.lang.String>
     * @throws IOException
     * @author wliduo[i@dolyw.com]
     * @date 2019/8/8 17:46
     */
    @PostMapping("/add")
    public Result<Object> add() throws IOException {
        // Endpoint直接指定为Index/Type的形式
        /*Request request = new Request("POST", new StringBuilder("/book/book/").toString());*/
        // 防重复新增数据
        Map<String,String> testMap = new HashMap<>(31);
        testMap.put("ID",String.valueOf(System.currentTimeMillis()));
        testMap.put("TESTVALUE","TESTVALUE");
        Request request = new Request("PUT", "/book/book/" +
                testMap.get("ID") + "/_create");
        // 设置其他一些参数比如美化Json
        request.addParameter("pretty", "true");
        // 设置请求体并指定ContentType,如果不指定会乱码
        request.setEntity(new NStringEntity(JSONObject.toJSONString(testMap), ContentType.APPLICATION_JSON));
        // 发送HTTP请求
        Response response = restClient.performRequest(request);
        // 获取响应体
        String responseBody = EntityUtils.toString(response.getEntity());
        return new ResultUtil<>().setData(JSONObject.parseObject(responseBody));
    }
}

XContentBuilder 使用方法https://blog.csdn.net/qq_39187822/article/details/110954406

好的,下面我来为你讲解如何在Spring Boot中整合ElasticsearchHigh Level Client,具体步骤如下: 1. 添加Elasticsearch依赖 在`pom.xml`文件中添加以下依赖: ```xml <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.15.1</version> </dependency> ``` 2. 配置Elasticsearch 在`application.properties`文件中添加以下配置: ```properties spring.elasticsearch.rest.uris=http://localhost:9200 # Elasticsearch的地址和端口 ``` 3. 创建Elasticsearch配置类 创建一个配置类,用于配置ElasticsearchHigh Level Client。例如: ```java @Configuration public class ElasticsearchConfig { @Value("${spring.elasticsearch.rest.uris}") private String esUris; @Bean public RestHighLevelClient restHighLevelClient() { String[] esUriArray = esUris.split(","); HttpHost[] httpHosts = new HttpHost[esUriArray.length]; for (int i = 0; i < esUriArray.length; i++) { httpHosts[i] = HttpHost.create(esUriArray[i]); } RestClientBuilder builder = RestClient.builder(httpHosts); return new RestHighLevelClient(builder); } } ``` 其中,`@Value`注解用于获取`application.properties`文件中的配置,`RestHighLevelClient`为ElasticsearchHigh Level Client。 4. 使用Elasticsearch 在代码中使用Elasticsearch时,只需要注入`RestHighLevelClient`,即可进行CRUD操作。例如: ```java @Autowired private RestHighLevelClient restHighLevelClient; public void save(String index, String id, String json) throws IOException { IndexRequest request = new IndexRequest(index).id(id).source(json, XContentType.JSON); restHighLevelClient.index(request, RequestOptions.DEFAULT); } public String findById(String index, String id) throws IOException { GetRequest request = new GetRequest(index).id(id); GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT); return response.getSourceAsString(); } public void update(String index, String id, String json) throws IOException { UpdateRequest request = new UpdateRequest(index, id).doc(json, XContentType.JSON); restHighLevelClient.update(request, RequestOptions.DEFAULT); } public void delete(String index, String id) throws IOException { DeleteRequest request = new DeleteRequest(index, id); restHighLevelClient.delete(request, RequestOptions.DEFAULT); } ``` 以上就是在Spring Boot中整合ElasticsearchHigh Level Client的详细步骤,希望能对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值