Spring4.3.5集成elasticsearch

Spring4.3.5集成elasticsearch
环境:
jdk:1.8
elasticsearch:6.4.2
maven地址:

	 
        org.elasticsearch
        elasticsearch
        5.6.0
    
	
	
	
        org.elasticsearch.client
        transport
        5.6.0
    

注意:elasticsearch:6.4.2最低需要5.6.0的版本,否则使用java连接会报错。

下面开始与spring集成,这边使用注解的方式:
新建一个spring-context-elasticsearch.xml配置文件,为了扫描注解。


  
     
    

base-package=“org.elasticsearch.spring” 定义了要扫描的包,这个包下面最好只放与elasticsearch初始化相关的配置类。

package org.elasticsearch.spring;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;



@Configuration
public class SpringConfiguration {

	private static final Log LOG = LogFactory.getLog(SpringConfiguration.class);
	
    //bean的id为transportClient
    @Bean
    public TransportClientFactory transportClient(){
    	LOG.info("初始化TransportClientFactory");
    	TransportClientFactory transportClientFactory=new TransportClientFactory();
        transportClientFactory.setClusterName("elasticsearch");
        transportClientFactory.setHost("127.0.0.1");
        transportClientFactory.setPort(9300);
        return transportClientFactory;
    }
}




package org.elasticsearch.spring;

import java.net.InetAddress;

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.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import com.esotericsoftware.minlog.Log;

public class TransportClientFactory implements FactoryBean, InitializingBean, DisposableBean {

	private String clusterName;
	private String host;
	private int port;
	private TransportClient client;

	public void setClusterName(String clusterName) {
		this.clusterName = clusterName;
	}

	public void setHost(String host) {
		this.host = host;
	}

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

	@Override
	public void destroy() throws Exception {
		if (client != null)
			client.close();

	}

	@Override
	public void afterPropertiesSet() throws Exception {
		Log.info("初始化TransportClientFactory");
		Settings settings = Settings.builder().put("cluster.name", this.clusterName).build();
		client = new PreBuiltTransportClient(settings)
				.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(this.host), this.port));
	}

	@Override
	public TransportClient getObject() throws Exception {
		return client;
	}

	@Override
	public Class getObjectType() {
		return TransportClient.class;
	}

	@Override
	public boolean isSingleton() {
		return false;
	}

}

将以上2个类放在org.elasticsearch.spring包下就OK 了。

你可能感兴趣的:(Spring4.3.5集成elasticsearch)