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;
}
}
}
}