步骤:

  1. 添加pom文件依赖
  2. 配置ElasticSearch
  3. 使用ElasticSearch的java客户端

一、添加pom文件依赖

<properties>
<elasticsearch.version>5.6.4</elasticsearch.version>
</properties>

<!-- elasticsearch -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${elasticsearch.version}</version>
</dependency>

<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>${elasticsearch.version}</version>
</dependency>

<!-- elasticsearch依赖,版本需要小于等于2.7 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>

二、配置ElasticSearch

package com.ahut.config;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
*
* @ClassName: ElasticSearchConfig
* @Description: elasticsearch配置
* @author cheng
* @date
@Configuration
public class ElasticSearchConfig

/**
*
* @Title: transportClient
* @Description: 配置elasticsearch
* @return
* @throws
@Bean
public TransportClient transportClient() throws UnknownHostException {
// 一定要注意,9300为elasticsearch的tcp端口
InetSocketTransportAddress master = new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300);
InetSocketTransportAddress node1 = new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9301);
InetSocketTransportAddress node2 = new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9302);
// 集群名称
Settings settings = Settings.builder().put("cluster.name", "rick").build();
TransportClient client = new PreBuiltTransportClient(settings);
// 添加
client.addTransportAddresses(master, node1, node2);
return

三、使用ElasticSearch的java客户端

dao层中注入:

/**
* ElasticSearch客户端
*/
@Autowired
private

工具类中注入:

/**
* ElasticSearch客户端,静态字段不同直接装配,这里通过set方法装配
*/
private static TransportClient client;

/**
*
* @Title: setClient
* @Description: spring注入静态字段
* @param
@Autowired
public void setClient