Elasticsearch【JAVA REST Client】客户端操作
ES系统作为集群,环境搭建非常方便简单。 现在在我们的应用中,如何对这个集群进行操作呢?
我们利用ES系统,通常都是下面的架构:

在这里,客户端的请求通过LB进行负载均衡,因为操作任何一个ES的实例,最终在ES集群系统中内容都是一样的,所以,考虑各个ES节点的负载问题以及容灾问题,上述的架构是当下最流行的方式。
下面,将要介绍ES JAVA REST API方式操作ES集群。
若是通过maven项目操作,相对比较简单的,只需要在pom.xml下面加入下面的配置
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>rest</artifactId>
<version>5.0.-rc1</version>
</dependency>
但是,我们公司网络让人蛋疼,maven仓库基本连接不上,所以,我们不得不采用Dynamic Web Project的方式,所以,需要的ES客户端jar包需要自己下载了。大家可以在maven的网站上一个个的下载,主要是依赖下载,可以在rest的下载地址下面,找到这个包的依赖文件,其实,就是httpclient的一些jar包。
commons-codec
commons-logging
httpclient
httpcore
httpasyncclient
httpcore-nio
这些包,都不大,下载后放在自己的工程lib下面即可。
我在项目TKSearch里面创建了一个测试用的controller文件SearchProducerController,然后在service下面创建一个接口文件IESRestService.java,并做相关实现ESRestService.java. 代码如下:
IESRestService.java
/**
* @author "shihuc"
* @date 2016年10月26日
*/
package com.tk.es.search.service; import org.apache.http.HttpEntity; /**
* @author chengsh05
*
*/
public interface IESRestService { /**
* 同步方式向ES集群写入数据
*
* @param index
* @param type
* @param id
* @param entity
* @return
*/
public boolean putSync(String index, String type, String id, HttpEntity entity); /**
* 异步的方式向ES写入数据
*
* @param index
* @param type
* @param id
* @param entity
* @return
*/
public void putAsync(String index, String type, String id, HttpEntity entity); }
ESRestService.java
/**
* @author "shihuc"
* @date 2016年10月26日
*/
package com.tk.es.search.service.impl; import java.io.IOException;
import java.util.Collections; import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy; import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseListener;
import org.elasticsearch.client.RestClient;
import org.springframework.stereotype.Service; import com.tk.es.search.service.IESRestService; /**
* @author chengsh05
*
*/
@Service
public class ESRestService implements IESRestService{ private RestClient restClient = null; /* (non-Javadoc)
* @see com.tk.es.search.service.IESRestService#putSync(java.lang.String, java.lang.String, java.lang.String, org.apache.http.HttpEntity)
*/
@Override
public boolean putSync(String index, String type, String id, HttpEntity entity) {
Response indexResponse = null;
try {
indexResponse = restClient.performRequest(
"PUT",
"/" + index + "/" + type + "/" + id,
Collections.<String, String>emptyMap(),
entity);
} catch (IOException e) {
e.printStackTrace();
}
return (indexResponse != null);
} @PostConstruct
public void init(){
restClient = RestClient.builder(new HttpHost("10.90.7.2", , "http")).build(); #这里builder的参数,可以是很多个HttpHost的数组,若采用博文开篇的架构图的话,这里的HttpHost就是LB的的地址
} @PreDestroy
public void destroy(){
if(restClient != null){
try {
restClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} /* (non-Javadoc)
* @see com.tk.es.search.service.IESRestService#putAsync(java.lang.String, java.lang.String, java.lang.String, org.apache.http.HttpEntity)
*/
@Override
public void putAsync(String index, String type, String id, HttpEntity entity) { restClient.performRequestAsync(
"PUT", #HTTP的方法,可以是PUT,POST,DELETE,HEAD,GET等
"/" + index + "/" + type + "/" + id, #endpoint, 这个就是指数据在ES中的位置,由index,type以及id确定
Collections.<String, String>emptyMap(), #是一个map
entity, #指的是操作数,即目标数据,这个例子里面表示要存入ES的数据对象
new ResponseListener() { #异步操作的监听器,在这里,注册listener,对操作成功或者失败进行后续的处理,比如在这里向前端反馈执行后的结果状态
@Override
public void onSuccess(Response response) {
System.out.println(response);
} @Override
public void onFailure(Exception exception) {
System.out.println("failure in async scenrio");
}
}); } }
SearchProducerController.java
/**
* @author "shihuc"
* @date 2016年10月26日
*/
package com.tk.es.search.controller; import java.util.HashMap; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import com.google.gson.Gson;
import com.tk.es.search.service.impl.ESRestService; /**
* @author chengsh05
*
*/
@Controller
public class SearchProducerController { @Resource
private ESRestService esRestService; @RequestMapping(value="/articleSync")
@ResponseBody
public String prepareArticleSync(HttpServletRequest req, HttpServletResponse rsp){
HttpEntity entity = new StringEntity(
"{\n" +
" \"user\" : \"kimchy\",\n" +
" \"post_date\" : \"2009-11-15T14:12:12\",\n" +
" \"message\" : \"trying out Elasticsearch\"\n" +
"}", ContentType.APPLICATION_JSON); esRestService.putSync("rest_index", "client", "", entity);
Gson gson = new Gson();
HashMap<String, String> res = new HashMap<String, String>();
res.put("result", "successful");
return gson.toJson(res);
} @RequestMapping(value="/articleAsync")
@ResponseBody
public String prepareArticleAsync(HttpServletRequest req, HttpServletResponse rsp){
HttpEntity entity = new StringEntity(
"{\n" +
" \"user\" : \"shihuc\",\n" +
" \"post_date\" : \"2016-10-26T13:30:12\",\n" +
" \"message\" : \"Demo REST Client to operate Elasticsearch\"\n" +
"}", ContentType.APPLICATION_JSON); esRestService.putAsync("rest_index", "client", "", entity);
Gson gson = new Gson();
HashMap<String, String> res = new HashMap<String, String>();
res.put("result", "successful");
return gson.toJson(res);
}
}
启动项目,在地址栏输入http://10.90.9.20:8080/TKSearch/articleSync将会以同步的方式在ES集群中创建一条记录。

输入http://10.90.9.20:8080/TKSearch/articleAsync,将会以异步的方式创建一个记录。

将RestClient以一个Service进行包装,在Spring启动的时候,注入bean过程中进行初始化,在bean销毁前进行连接的关闭操作。利用Spring支持的两个注解@PostConstruct和@PreDestroy完成连接的建立和销毁,结构干净简单。
到此,客户端以Java REST Client的方式操作ES集群的demo就演示结束。 后续将介绍Elasticsearch Java API的方式操作ES集群的实施过程。
Elasticsearch【JAVA REST Client】客户端操作的更多相关文章
- Elasticsearch Java Rest Client API 整理总结 (二) —— SearchAPI
目录 引言 Search APIs Search API Search Request 可选参数 使用 SearchSourceBuilder 构建查询条件 指定排序 高亮请求 聚合请求 建议请求 R ...
- Elasticsearch Java Rest Client API 整理总结 (三)——Building Queries
目录 上篇回顾 Building Queries 匹配所有的查询 全文查询 Full Text Queries 什么是全文查询? Match 全文查询 API 列表 基于词项的查询 Term Term ...
- Elasticsearch Java Rest Client API 整理总结 (一)——Document API
目录 引言 概述 High REST Client 起步 兼容性 Java Doc 地址 Maven 配置 依赖 初始化 文档 API Index API GET API Exists API Del ...
- Elasticsearch Java Rest Client简述
ESJavaClient的历史 JavaAPI Client 优势:基于transport进行数据访问,能够使用ES集群内部的性能特性,性能相对好 劣势:client版本需要和es集群版本一致,数据序 ...
- java web 获取客户端操作系统信息
package com.java.basic.pattern; import java.util.regex.Matcher; import java.util.regex.Pattern; /** ...
- 使用Jedis操作Redis-使用Java语言在客户端操作---set类型
原文地址:http://www.cnblogs.com/lixianyuan-org/p/9509696.html 1 //测试set数据类型 2 /** 3 * 在Redis中,我们可以将Set类型 ...
- 使用Jedis操作Redis-使用Java语言在客户端操作---对Sorted-Sets的操作
//对Sorted-Sets操作 /** * Sorted-Sets和Sets类型极为相似,它们都是字符串的集合,都不允许重复的成员出现在一个Set中. * 它们之间的主要差别是Sorted-Sets ...
- 使用Jedis操作Redis-使用Java语言在客户端操作---hash类型
我们可以将Redis中的Hashes类型看成具有String Key和String Value的map容器. 所以该类型非常适合于存储值对象的信息.如Username.P ...
- 使用Jedis操作Redis-使用Java语言在客户端操作---List类型
在Redis中,List类型是按照插入顺序排序的字符串链表.和数据结构中的普通链表一样,我们可以在其头部(left)和尾部(right)添加新的元素.在插入时,如果该键并不存在,Redis将为该键创建 ...
- 使用Jedis操作Redis-使用Java语言在客户端操作---String类型
前提:需要引入Jedis的jar包. /** * 我的redis在Linux虚拟机Centos7中,192.168.222.129是我虚拟机的ip地址. */ private static Jedis ...
随机推荐
- Python学习路程day21
本节内容: 项目实战:开发一个WEB聊天室 功能需求: 用户可以与好友一对一聊天 可以搜索.添加某人为好友 用户可以搜索和添加群 每个群有管理员可以审批用户的加群请求,群管理员可以用多个,群管理员可以 ...
- 2016 - 1 - 25 CSS初步 (二)
1.The customising link We can change the link's style when we move our pointer on the link like that ...
- Hadoop YARN中内存的设置
在YARN中,资源管理由ResourceManager和NodeManager共同完成,其中,ResourceManager中的调度器负责资源的分配,而NodeManager则负责资源的供给和隔离.R ...
- C语言格式化输入不定长数组
先随便写写,有空再整理. 直接贴代码 #include <stdio.h> #include <stdlib.h> //从一行标准输入中格式化输入一个不定长数组 void in ...
- 基于数据库MySQL的简易学生信息管理系统
通过这几天学习Mysql数据库,对其也有了基本的了解,为了加深印象,于是就写了一个最简易的学生信息管理系统. 一:基本要求 1.通过已知用户名和密码进行登录: 2.可以显示菜单: 3.可以随时插入学生 ...
- 个人Web工具箱&资源整理(1)
很久就想把使用的工具及收藏的资源整理一番:一是为了传达博客社区的理念:资源共享,而是方便自己及团队快速获取. 学习资源: 首推两个入门级在线参考网站. 1 w3c school. 2 Runoob.c ...
- Android手机刷机失败的自救方法
刷机对于一些android手机的高级用户来说已经是家常便饭了,很多新手也都跟着教程轻松了学会刷机.升级系统,也都开始经常在网上搜罗一些自制的系统进行刷机,体验新系统带来的新感觉.但是有句古话叫常在河边 ...
- MATLAB plot 绘图的一些经验,记下来,facilitate future work
[转载请注明出处]http://www.cnblogs.com/mashiqi 2016/03/28 % 调整figure的位置scrsz = get(0,'ScreenSize'); % 这个命令是 ...
- Day24_多线程第一天
1.线程 1.概述 宏观来讲 进程:就是正在运行的程序 线程:就是进程的执行路径,执行单元 2.创建并启动线程的两种方式(掌握) 1.定义一个类继承Thread ...
- 3-Spark高级数据分析-第三章 音乐推荐和Audioscrobbler数据集
偏好是无法度量的. 相比其他的机器学习算法,推荐引擎的输出更直观,更容易理解. 接下来三章主要讲述Spark中主要的机器学习算法.其中一章围绕推荐引擎展开,主要介绍音乐推荐.在随后的章节中我们先介绍S ...