首页 技术 正文
技术 2022年11月6日
0 收藏 362 点赞 913 浏览 5492 个字

ES系统作为集群,环境搭建非常方便简单。 现在在我们的应用中,如何对这个集群进行操作呢?

我们利用ES系统,通常都是下面的架构:

Elasticsearch【JAVA REST Client】客户端操作

在这里,客户端的请求通过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集群中创建一条记录。

Elasticsearch【JAVA REST Client】客户端操作

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

Elasticsearch【JAVA REST Client】客户端操作

将RestClient以一个Service进行包装,在Spring启动的时候,注入bean过程中进行初始化,在bean销毁前进行连接的关闭操作。利用Spring支持的两个注解@PostConstruct和@PreDestroy完成连接的建立和销毁,结构干净简单。

到此,客户端以Java REST Client的方式操作ES集群的demo就演示结束。 后续将介绍Elasticsearch Java API的方式操作ES集群的实施过程。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,023
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,513
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,361
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,143
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,774
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,853