ElasticSearch学习 - (五)SpringBoot集成ElasticSearch5.X

步骤:

  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 2017年12月28日 下午5:34:23
 */
@Configuration
public class ElasticSearchConfig {

    /**
     * 
     * @Title: transportClient
     * @Description: 配置elasticsearch
     * @return
     * @throws UnknownHostException
     */
    @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 client;
    }

}

三、使用ElasticSearch的java客户端

dao层中注入:

/**
 * ElasticSearch客户端
 */
@Autowired
private TransportClient client;

工具类中注入:

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

/**
 * 
 * @Title: setClient 
 * @Description: spring注入静态字段
 * @param client
 */
@Autowired
public void setClient (TransportClient client) {
    工具类名称.client = client;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值