1、maven
<!-- Java Low Level REST Client -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>6.4.0</version>
</dependency>
2、創建ResfClientUtil
package com.yj.framework.es.util;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
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.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.io.IOException;
public class ResfClientUtil {
/**
* 增加、刪除、id查詢
* @param method "POST" or "GET" or "DELETE" .....
* @param indexType "/book/book/" or "book/book/"
* @param id
* @param object
* @return
*/
public static ResponseEntity<String> client(RestClient client,String method,String indexType,String id,Object object){
// 構造HTTP請求,第一個參數是請求方法,第二個參數是服務器的端點,
// endpoint直接指定爲index/type的形式
Request request = new Request(method, new StringBuilder(indexType).append(id).toString());
return clientRequest(client,request,object);
}
public static ResponseEntity<String> client(RestClient client,String method,String indexType,Object object){
// 構造HTTP請求,第一個參數是請求方法,第二個參數是服務器的端點,
// endpoint直接指定爲index/type的形式
Request request = new Request(method, new StringBuilder(indexType).toString());
return clientRequest(client,request,object);
}
public static ResponseEntity<String> client(RestClient client,String method,String indexType,String id,String str){
// 構造HTTP請求,第一個參數是請求方法,第二個參數是服務器的端點,
// endpoint直接指定爲index/type的形式
Request request = new Request(method, new StringBuilder(indexType).append(id).toString());
return clientRequest(client,request,str);
}
public static ResponseEntity<String> client(RestClient client,String method,String indexType,String str){
// 構造HTTP請求,第一個參數是請求方法,第二個參數是服務器的端點,
// endpoint直接指定爲index/type的形式
Request request = new Request(method, new StringBuilder(indexType).toString());
return clientRequest(client,request,str);
}
/**
* 並行異步執行HTTP請求
*/
public static void clientAsyn(RestClient client,String method,String indexType,String id,Object object,ResfTask resfTask) {
Request request = new Request(method, indexType + id);
//let's assume that the documents are stored in an HttpEntity array
request.setEntity(new NStringEntity(new JSONObject(object).toString(), ContentType.APPLICATION_JSON));
client.performRequestAsync(request,new ResponseListener() {
@Override
public void onSuccess(Response response) {
resfTask.successTash(response);
}
@Override
public void onFailure(Exception exception) {
resfTask.errorTash(exception);
}
});
}
/**
* 根據id更新object
* @param id
* @param object
* @return
*/
public static ResponseEntity<String> updateById(RestClient client,String method,String indexType,String id,Object object) {
// 構造HTTP請求
Request request = new Request(method, new StringBuilder(indexType).append(id).append("/_update").toString());
request.addParameter("pretty", "true");
// 將數據丟進去,這裏一定要外包一層“doc”,否則內部不能識別
JSONObject jsonObject = new JSONObject();
jsonObject.put("doc", new JSONObject(object));
request.setEntity(new NStringEntity(jsonObject.toString(),ContentType.APPLICATION_JSON));
return performRequest(client,request);
}
/**
* 查詢
* @param
* @return
*/
public static ResponseEntity<String> select(RestClient client,String method,String indexType,String str) {
// 構造HTTP請求
Request request = new Request(method, new StringBuilder(indexType).append("/_search").toString());
request.addParameter("pretty", "true");
// 將數據丟進去,這裏一定要外包一層“doc”,否則內部不能識別
request.setEntity(new NStringEntity(str,ContentType.APPLICATION_JSON));
return performRequest(client,request);
}
/**
*
* @param client
* @param method
* @param indexType
* @param id
* @param str new JSONObject(object) object爲對象
* @return
*/
public static ResponseEntity<String> updateById(RestClient client,String method,String indexType,String id,String str) {
// 構造HTTP請求
Request request = new Request(method, new StringBuilder(indexType).append(id).append("/_update").toString());
request.addParameter("pretty", "true");
// 將數據丟進去,這裏一定要外包一層“doc”,否則內部不能識別
JSONObject jsonObject = new JSONObject();
jsonObject.put("doc", str);
request.setEntity(new NStringEntity(jsonObject.toString(),ContentType.APPLICATION_JSON));
return performRequest(client,request);
}
public static ResponseEntity<String> clientRequest(RestClient client, Request request,Object object){
// 設置其他一些參數比如美化json
request.addParameter("pretty", "true");
if(null!=object){
// 設置請求體並指定ContentType,如果不指定默認爲ContentType.APPLICATION_JSON
request.setEntity(new NStringEntity(new JSONObject(object).toString(), ContentType.APPLICATION_JSON));
}
return performRequest(client,request);
}
public static ResponseEntity<String> clientRequest(RestClient client, Request request,String str){
// 設置其他一些參數比如美化json
request.addParameter("pretty", "true");
if(null!=str){
// 設置請求體並指定ContentType,如果不指定默認爲ContentType.APPLICATION_JSON
request.setEntity(new NStringEntity(str, ContentType.APPLICATION_JSON));
}
return performRequest(client,request);
}
/**
* 執行HTTP請求
* @param request
* @return
*/
public static ResponseEntity<String> performRequest(RestClient client,Request request){
try {
// 執行HTTP請求
Response response = client.performRequest(request);
// 獲取返回的內容
String responseBody = EntityUtils.toString(response.getEntity());
return new ResponseEntity<>(responseBody, HttpStatus.OK);
} catch (IOException e) {
return null;
}
}
}
3、創建ResfTask
package com.yj.framework.es.util;
import org.elasticsearch.client.Response;
public interface ResfTask {
void successTash(Response response);
void errorTash(Exception exception);
}
4、創建ResfClienService
package com.yj.framework.es.service;
import com.yj.framework.es.util.ResfTask;
import org.springframework.http.ResponseEntity;
public interface ResfClienService {
/**
* 添加ES對象, Book的ID就是ES中存儲的document的ID,所以最好不要爲空,自定義生成的ID太浮誇
*/
ResponseEntity<String> add(String indexType, String id, Object object);
ResponseEntity<String> add(String indexType,String id,String str);
ResponseEntity<String> add(String indexType,Object object);
ResponseEntity<String> add(String indexType,String str);
/**
* 並行異步執行HTTP請求
*/
void addAsyn(String method, String indexType, String id, Object object, ResfTask resfTask);
/**
* 根據id獲取ES對象
*/
ResponseEntity<String> getById(String indexType,String id);
/**
* 根據id更新Book
*/
ResponseEntity<String> updateById(String indexType,String id,Object object);
ResponseEntity<String> updateById(String indexType,String id,String str);
ResponseEntity<String> deleteById(String indexType,String id);
ResponseEntity<String> select(String indexType,String str);
}
5、創建ResfClienServiceImpl
package com.yj.framework.es.service.impl;
import com.yj.framework.es.service.ResfClienService;
import com.yj.framework.es.util.ResfTask;
import com.yj.framework.es.util.ResfClientUtil;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import java.io.IOException;
@Service
public class ResfClienServiceImpl implements ResfClienService {
@Autowired
private RestClient client;
// RequestOptions類保存應在同一應用程序中的多個請求之間共享的部分請求
// private 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();
// }
//
// @RequestMapping(value = "/go", method = RequestMethod.GET)
// public ResponseEntity<String> go() {
// return new ResponseEntity<>("go", HttpStatus.OK);
// }
/**
* 同步執行HTTP請求
*
* @return
* @throws IOException
*/
/* public ResponseEntity<String> getEsInfo() throws IOException {
// 構造HTTP請求,第一個參數是請求方法,第二個參數是服務器的端點,host默認是http://localhost:9200
Request request = new Request("POST", "book/book");
// // 設置其他一些參數比如美化json
// request.addParameter("pretty", "true");
// // 設置請求體
request.setEntity(new NStringEntity("{\"query\":{\"bool\":{\"must\":[{\"term\":{\"name\":\"8\"}}],\"must_not\":[],\"should\":[]}},\"from\":0,\"size\":250,\"sort\":[],\"aggs\":{}}", ContentType.APPLICATION_JSON));
// // 還可以將其設置爲String,默認爲ContentType爲application/json
// request.setJsonEntity("{\"query\":{\"bool\":{\"must\":[{\"term\":{\"name\":\"8\"}}],\"must_not\":[],\"should\":[]}},\"from\":0,\"size\":250,\"sort\":[],\"aggs\":{}}");
*//*
performRequest是同步的,將阻塞調用線程並在請求成功時返回Response,如果失敗則拋出異常
內部屬性可以取出來通過下面的方法
*//*
Response response = client.performRequest(request);
// // 獲取請求行
// RequestLine requestLine = response.getRequestLine();
// // 獲取host
// HttpHost host = response.getHost();
// // 獲取狀態碼
// int statusCode = response.getStatusLine().getStatusCode();
// // 獲取響應頭
// Header[] headers = response.getHeaders();
// 獲取響應體
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;
}*/
@Override
public ResponseEntity<String> add(String indexType,String id,Object object){
return ResfClientUtil.client(client,"POST",indexType,id,object);
}
@Override
public ResponseEntity<String> add(String indexType,String id,String str){
return ResfClientUtil.client(client,"POST",indexType,id,str);
}
@Override
public ResponseEntity<String> add(String indexType,Object object){
return ResfClientUtil.client(client,"POST",indexType,object);
}
@Override
public ResponseEntity<String> add(String indexType,String str){
return ResfClientUtil.client(client,"POST",indexType,str);
}
@Override
public void addAsyn(String method, String indexType, String id, Object object, ResfTask resfTask) {
ResfClientUtil.clientAsyn(client,indexType,indexType,id,object,resfTask);
}
@Override
public ResponseEntity<String> getById(String indexType,String id) {
return ResfClientUtil.client(client,"GET",indexType,id,null);
}
@Override
public ResponseEntity<String> updateById(String indexType,String id,Object object){
return ResfClientUtil.updateById(client,"POST",indexType,id,object);
}
public ResponseEntity<String> updateById(String indexType,String id,String str){
return ResfClientUtil.updateById(client,"POST",indexType,id,str);
}
@Override
public ResponseEntity<String> deleteById(String indexType,String id){
return ResfClientUtil.client(client,"DELETE",indexType,id,null);
}
@Override
public ResponseEntity<String> select(String indexType,String str){
return ResfClientUtil.select(client,"GET",indexType,str);
}
}