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 ...
随机推荐
- iOS-打电话、发短信、发邮件、打开浏览器
- (IBAction)showAlert:(UIButton *)sender { NSString *phoneNumber=@"18500138888"; NSString ...
- xamarin for android 生成时“java.exe已退出 代码为1”
Xamarin Studio中创建了一个Android Application 运行时出现错误:C:\Program Files\MSBuild\Xamarin\Android\Xamarin.And ...
- 学习SVG系列(5):SVG渐变
SVG渐变 渐变是一种从一种颜色到另一种颜色的平滑过渡,可以把多个颜色的过渡应用到同一个元素. 渐变有两种: Linear Redial 线性渐变-<linearGradient> lin ...
- renderman、arnold及全局光照
走马观花看了一些实现全局光(global illumination)的文章,都是非实时电影级的.的确可以分为两个阵营,一是pixar的renderman中常用的reyes+点云,感觉pixar一路走来 ...
- 解决iOS9下隐藏App返回按钮文字导致的诡异闪屏问题
问题的原因竟是一行代码导致的,这行代码的作用是隐藏App返回按钮的文字. 看看这有问题的代码: //将返回按钮的文字position设置不在屏幕上显示 [[UIBarButtonItem appear ...
- DIPHA
https://github.com/DIPHA/dipha http://www.rkwitt.org/blog/topological_machine_learning.html 一.预装软件 1 ...
- 一道google面试题
输入n,把1-n分成两个和相等的子集,有多少种分法 想了个dp,直接背包也行 #include <iostream> #include <cstdio> using names ...
- 关于discuz“终于解决“头像保存过程中发生网络错误,请重试"”的解决方法
1 php.ini里面allow_url_fopen = On2 将php.ini中的;upload_tmp_dir = 该行的注释符,即前面的分号“:”去掉,使该行在php.ini文档中起作用.up ...
- ionic 打包签名
IONIC用一下命令打包会自动签名并且打包 ionic build android 自己签名并且打包方法: 1>在你项目app\platforms\android目录下新建文件:debug-si ...
- android 手机屏幕有关的几个工具(屏幕宽高,dp和px互相转换)
平时适配页面时经常会需要根据屏幕的宽高来设置控件的大小,很多时候在代码中还会需要dp和px互相转换. 今天把最常用的几个记录一下,经测试包括2.3 ~ 5.0之间的版本都可用,其他版本未测,不过应该也 ...