java使用transportClient连接elasticsearch并做接口实现增删改查ES6.4.3版本

作者: admin 分类: ELK 发布时间: 2019-03-27 22:50  阅读: 265 views

阶段性学习elasticsearch,前期做了日志的分析与监控, ELK环境搭建之filebeat根据不同的监控日志文件建立不同的索引

整体效果不错,线上日志的错误能够及时的通过发送邮件,查看环境搭建之linux下ELK搭建好之后配置sentinl插件,进行邮件告警

对于公司线上的程序运行情况的监控以及发布时的验证有明显的帮助。由于是部署在独立服务器,只是监控日志显得有点浪费,所以计划将搜索业务的数据转移到es中,方便即是查询和分词检索。以下是简单的依赖配置和接口的定义、实现

<!-- pom 依赖 -->
<dependency>
	<groupId>org.elasticsearch</groupId>
	<artifactId>elasticsearch</artifactId>
	<version>6.4.3</version>
</dependency>

<dependency>
	<groupId>org.elasticsearch.client</groupId>
	<artifactId>transport</artifactId>
	<version>6.4.3</version>
</dependency>

接口的定义

package com.elasticsearch.service;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;

public abstract interface ElasticsearchService
{
  //获取TransprotClient对象
  public abstract TransportClient getTransportClient();
  //搜索业务一
  public abstract SearchResponse getSearchResult(SearchRequest paramSearchRequest);
  //搜索业务二
  public abstract SearchResponse getSearchResult(String paramString1, String paramString2, SearchSourceBuilder paramSearchSourceBuilder);
  //搜索业务三
  public abstract SearchResponse getSearchResult(String paramString1, String paramString2, Integer paramInteger1, Integer paramInteger2, String paramString3, QueryBuilder paramQueryBuilder, AggregationBuilder paramAggregationBuilder);
  //新增或修改索引
  public abstract boolean updateIndexRequest(String paramString1, String paramString2, String paramString3, String paramString4);
  //删除索引
  public abstract boolean deleteIndex(String paramString1, String paramString2, String paramString3);
}

接口的实现,java与elasticsearch的连接通过实现spring的InitializingBean接口进行初始化

package com.elasticsearch.service.impl;

import com.elasticsearch.service.ElasticsearchService;
import java.net.InetAddress;
import java.util.concurrent.ExecutionException;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.DocWriteResponse.Result;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.InitializingBean;

public class ElasticsearchServiceImpl
  implements ElasticsearchService, InitializingBean
{
  private String ip;
  private int port;
  private TransportClient client;

  public String getIp()
  {
    return this.ip;
  }

  public void setIp(String ip) {
    this.ip = ip;
  }

  public int getPort() {
    return this.port;
  }

  public void setPort(int port) {
    this.port = port;
  }

  public TransportClient getTransportClient() {
    return this.client;
  }

  public SearchResponse getSearchResult(SearchRequest request) {
    return (SearchResponse)this.client.search(request).actionGet();
  }

  public SearchResponse getSearchResult(String indexName, String typeName, SearchSourceBuilder searchSourceBuilder)
  {
    return 
      (SearchResponse)this.client.search(new SearchRequest()
      .indices(new String[] { indexName })
      .types(new String[] { typeName })
      .source(searchSourceBuilder))
      .actionGet();
  }

  public SearchResponse getSearchResult(String indexName, String typeName, Integer page, Integer pageSize, String sortDesc, QueryBuilder queryBuilder, AggregationBuilder aggregationBuilder)
  {
    return 
      (SearchResponse)this.client.search(new SearchRequest()
      .indices(new String[] { indexName })
      .types(new String[] { typeName })
      .source(new SearchSourceBuilder()
      .query(queryBuilder)
      .from(page
      .intValue() * pageSize.intValue())
      .size(pageSize
      .intValue())
      .sort(sortDesc, SortOrder.DESC)
      .aggregation(aggregationBuilder)))
      .actionGet();
  }

  public boolean updateIndexRequest(String indexName, String typeName, String id, String jsonStr)
  {
    IndexRequest createRequest = new IndexRequest(indexName, typeName, id);
    createRequest.source(jsonStr, XContentType.JSON);
    UpdateRequest updateRequest = new UpdateRequest(indexName, typeName, id);
    updateRequest.doc(jsonStr, XContentType.JSON)
      .upsert(createRequest);
    try
    {
      UpdateResponse updateResponse = (UpdateResponse)this.client.update(updateRequest).get();
      if ((updateResponse.getResult().getLowercase().equals("updated")) || 
        (updateResponse
        .getResult().getLowercase().equals("created")))
        return true;
    }
    catch (InterruptedException e) {
      e.printStackTrace();
    } catch (ExecutionException e) {
      e.printStackTrace();
    }

    return false;
  }

  public boolean deleteIndex(String indexName, String typeName, String id) {
    DeleteRequest deleteRequest = new DeleteRequest(indexName, typeName, id);
    try {
      DeleteResponse deleteResponse = (DeleteResponse)this.client.delete(deleteRequest).get();
      if (deleteResponse.getResult().getLowercase().equals("deleted"))
        return true;
    }
    catch (InterruptedException e) {
      e.printStackTrace();
    } catch (ExecutionException e) {
      e.printStackTrace();
    }
    return false;
  }

  public void afterPropertiesSet() throws Exception
  {
    this.client = new PreBuiltTransportClient(Settings.EMPTY, new Class[0])
      .addTransportAddress(new TransportAddress(
      InetAddress.getByName(this.ip), 
      this.port));
  }
}

spring.xml配置,配置信息放到properties文件中或者其他配置中心

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
	xmlns:c="http://www.springframework.org/schema/c"  
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
	      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 
	      http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.2.xsd">
	
	<!-- ES -->
	<bean id="elasticsearchService" class="com.kaishiba.elasticsearch.service.impl.ElasticsearchServiceImpl" >
		<property name="ip" value="${elasticsearch.ip}" />
		<property name="port" value="${elasticsearch.port}" />
	</bean>

</beans>  

 

基本就可以了,整体使用简单,对于我的业务实现基本足够。更多ES操作请参考官网【官方最靠谱】或相关笔记

 

 


   原创文章,转载请标明本文链接: java使用transportClient连接elasticsearch并做接口实现增删改查ES6.4.3版本

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发表评论

电子邮件地址不会被公开。 必填项已用*标注

更多阅读