springboot 集成ES笔记

springboot 集成:

采用万能版本兼容方法RestClient

        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-client</artifactId>
        <version>6.4.0</version>
    </dependency>
    <!--引入json进行HTTP序列化-->
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20160810</version>
    </dependency>

1.配置

package com.example.esdemo.esdemo;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RestConfig {
    @Bean
    public RestClient getClient() {
        // 如果有多个从节点可以持续在内部new多个HttpHost,参数1是ip,参数2是HTTP端口,参数3是通信协议
        RestClientBuilder clientBuilder = RestClient.builder(new HttpHost("47.99.xx.xx", 9200, "http"));

        // 添加其他配置,返回来的还是RestClientBuilder对象,这些配置都是可选的
        // clientBuilder.setXX()...

        // 最后配置好的clientBuilder再build一下即可得到真正的Client
        return clientBuilder.build();
    }
}

2.控制器:

package com.example.esdemo.esdemo;

import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.util.Strings;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseListener;
import org.elasticsearch.client.RestClient;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

@RestController
@RequestMapping("/rest/stu")
public class StuController {
    @Qualifier("getClient")
    @Autowired
    private RestClient client;

    @RequestMapping(value = "/go", method = RequestMethod.GET)
    public ResponseEntity<String> go() {
        return new ResponseEntity<>("go", HttpStatus.OK);
    }

    /**
     * 同步执行HTTP请求
     *
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/es/{index}/{type}", method = RequestMethod.GET)
    public ResponseEntity<String> getEsInfo(@PathVariable String index, @PathVariable String type) throws IOException {
        // 构造HTTP请求,第一个参数是请求方法,第二个参数是服务器的端点,host默认是http://localhost:9200
        String endpoint = "/" + index + "/" + type + "/_search";
        if (Strings.isBlank(type)) {
            endpoint = "/" + index + "/_search";
        }
        Response response = client.performRequest("GET", endpoint);
        String responseBody = EntityUtils.toString(response.getEntity());
        return new ResponseEntity<>(responseBody, HttpStatus.OK);
    }


    /**
     * 异步执行HTTP请求
     *
     * @return
     */
    @RequestMapping(value = "/es/asyn", method = RequestMethod.GET)
    public ResponseEntity<String> asynchronous() {
        Request request = new Request(
                "GET",
                "/");
        client.performRequestAsync(request, new ResponseListener() {
            @Override
            public void onSuccess(Response response) {
                System.out.println("异步执行HTTP请求并成功");
            }

            @Override
            public void onFailure(Exception exception) {
                System.out.println("异步执行HTTP请求并失败");
            }
        });
        return null;
    }


    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResponseEntity<String> add(@RequestBody Stu stu) throws IOException {
        // 构造HTTP请求,第一个参数是请求方法,第二个参数是服务器的端点,host默认是http://localhost:9200,
        // endpoint直接指定为index/type的形式
        Request request = new Request("POST", new StringBuilder("/student_es/stu/").
                append(stu.getId()).toString());
        // 设置其他一些参数比如美化json
        request.addParameter("pretty", "true");

        JSONObject jsonObject = new JSONObject(stu);
        System.out.println(jsonObject.toString());
        // 设置请求体并指定ContentType,如果不指定默认为APPLICATION_JSON
        request.setEntity(new NStringEntity(jsonObject.toString()));

        // 发送HTTP请求


        Response response = client.performRequest(request);

        // 获取响应体, id: AWXvzZYWXWr3RnGSLyhH
        String responseBody = EntityUtils.toString(response.getEntity());
        return new ResponseEntity<>(responseBody, HttpStatus.OK);
    }

    /**
     * 根据id获取ES对象
     *
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/selectById", method = RequestMethod.POST)
    public ResponseEntity<String> getBookById(@RequestBody SelectBean selectBean) {
        Request request = new Request("POST", new StringBuilder("/student_es/stu/_search").toString());
        // 设置其他一些参数比如美化json
        request.addParameter("pretty", "true");
        // 发送HTTP请求
        Response response = null;
        String responseBody = null;
        try {
            request.setEntity(new NStringEntity(new JSONObject(selectBean).toString()));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            response = client.performRequest(request);
            responseBody = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            return new ResponseEntity<>("can not found the stu by your id", HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<>(responseBody, HttpStatus.OK);
    }

    /**
     * 根据id更新Book
     *
     * @param id
     * @param book
     * @return
     */
    @RequestMapping(value = "/updateById/{id}", method = RequestMethod.POST)
    public ResponseEntity<String> updateBook(@PathVariable String id, @RequestBody Stu book) throws IOException {
        // 构造HTTP请求
        Request request = new Request("POST", new StringBuilder("/student_es/stu/").
                append(id).append("/_update").toString());
        request.addParameter("pretty", "true");

        // 将数据丢进去,这里一定要外包一层“doc”,否则内部不能识别
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("doc", new JSONObject(book));
        request.setEntity(new NStringEntity(jsonObject.toString()));

        // 执行HTTP请求
        Response response = client.performRequest(request);

        // 获取返回的内容
        String responseBody = EntityUtils.toString(response.getEntity());

        return new ResponseEntity<>(responseBody, HttpStatus.OK);
    }


    @RequestMapping(value = "deleteById/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<String> deleteById(@PathVariable String id) throws IOException {
        Request request = new Request("DELETE", new StringBuilder("/student_es/stu/").append(id).toString());
//        request.addParameter("pretty", "true");
        // 执行HTTP请求
        Response response = client.performRequest(request);
        // 获取结果
        String responseBody = EntityUtils.toString(response.getEntity());

        return new ResponseEntity<>(responseBody, HttpStatus.OK);
    }
}

4.相关model:

package com.example.esdemo.esdemo;

public class Stu {
    private  long id;
    private int stu_age;
    private String stu_name;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public int getStu_age() {
        return stu_age;
    }

    public void setStu_age(int stu_age) {
        this.stu_age = stu_age;
    }

    public String getStu_name() {
        return stu_name;
    }

    public void setStu_name(String stu_name) {
        this.stu_name = stu_name;
    }
}

package com.example.esdemo.esdemo;


import java.io.Serializable;

public class SelectBean {


    /**
     * query : {"match":{"id":"9527"}}
     */

    private QueryBean query;

    public QueryBean getQuery() {
        return query;
    }

    public void setQuery(QueryBean query) {
        this.query = query;
    }

    public static class QueryBean implements Serializable {
        /**
         * match : {"id":"9527"}
         */

        private MatchBean match;

        public MatchBean getMatch() {
            return match;
        }

        public void setMatch(MatchBean match) {
            this.match = match;
        }

        public static class MatchBean implements Serializable {
            /**
             * id : 9527
             */

            private String id;

            public String getId() {
                return id;
            }

            public void setId(String id) {
                this.id = id;
            }
        }
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江南一舟110

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值