ElasticSearch 与 Java-spring 集成使用

1. Maven依赖:

ES 5.6.0最好搭配 log4j 2.7的版本,否则启动会提示Warning ;
##  版本
 
	5.6.0 	 	
	2.7 



            org.elasticsearch.client
            transport
            ${elasticsearch.version}


            org.apache.logging.log4j
            log4j-core
            ${log4j.version}

2. application-contextn.xml 中配置:

这里为了考虑集群的配置方式,所以application-context.xml中配置的nodeIpInfo是:ip+port;

这里没有使用注解的方式。而是最原始的添加bean,并配置初始化方式 init
  
	
// 自定义初始化Es的Bean :com.paytend.ccgateway.api.elastic.EsClientBuilder 
// EsClientBuilder有两个属性:clusterName nodeIpInfo
// clusterName:定义了es的集群名称,要和es服务器中 elasticsearch.yml中配置的 cluster.name 一致
//##1. nodeIpInfo:是连接es的ip和端口,常用端口9200 例:192.168.111.111:9200
  
	  
	  

//##2.当然这里的值可以放在配置文件,elasticsearch.yml中,spring加载配置文件
classpath:elasticsearch.yml
		  cluster.name:xxx.mingcheng
		  cluster.network:192.168.111.111:9200
  
	  
	  

//##3.在代码中,我是写死的配置。大家实际使用中。如果不需要多ip配置,可以把ip和port分别配置为属性注入Bean中即可。
classpath:elasticsearch.yml
		  cluster.name:xxx.mingcheng
		  cluster.ip:192.168.111.111
		  cluster.port:9200
 ## 或
  
	  
	  
	 

3.初始化Bean-Code

//初始化完成之后,只需要通过@Autowired注入即可使用
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;  
public class EsClientBuilder {  
	
	private static final Logger LOGGER = LoggerFactory.getLogger(EsClientBuilder.class);
  
  
    private String clusterName;  
    private String nodeIpInfo;  
    private TransportClient client;  
  
    /**java连接es注意事项 :
     * 1.端口号不能与HTTP设置的端口号一致!!!!  例如:HTTP 192.168.116.129:9200  这里需配置为 192.168.116.129:9300,客户端默认端口
     * 2.cluster.name 需与 es/config/elasticsearch.yml配置文件中的cluster.name 一致
     * 
     * 否则会报:NoNodeAvailableException
     */
    public Client init(){  
        //设置集群的名字  
    	TransportAddress transportAddress = null;
        try {
            Settings settings = Settings.builder()
            						 	.put("cluster.name", clusterName)
            						 	.build();
            client = new PreBuiltTransportClient(settings);
            transportAddress = new InetSocketTransportAddress(InetAddress.getByName("192.168.116.129"), 9300);
            client.addTransportAddress(transportAddress);
        } catch (Exception e) {
            LOGGER.error("获取服务地址失败,异常信息:{}", e.getMessage());
        }
        if (null == transportAddress) {
            LOGGER.error("获取服务地址失败,服务地址不可用!");
            return null;
        }
        return client;
        
        //创建集群client并添加集群节点地址  集群没测试,大家可自行测试
	//  Settings settings = Settings.builder()  
	//							    .put("client.transport.sniff", false)  
	//							    .put("cluster.name", clusterName)  
	//							    .build();  
	//	client = new PreBuiltTransportClient(settings);
	//	Map nodeMap = parseNodeIpInfo();  
	//	for (Map.Entry entry : nodeMap.entrySet()){  
	//		try {  
	//			client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(entry.getKey()), entry.getValue()));  
	//		} catch (UnknownHostException e) {  
	//			e.printStackTrace();  
	//		}  
	//	}  
	//	return client; 
    }  
  
    // 解析节点IP信息,多个节点用逗号隔开,IP和端口用冒号隔开 
    private Map parseNodeIpInfo(){  
        String[] nodeIpInfoArr = nodeIpInfo.split(",");  
        Map map = new HashMap(nodeIpInfoArr.length);  
        for (String ipInfo : nodeIpInfoArr){  
            String[] ipInfoArr = ipInfo.split(":");  
            map.put(ipInfoArr[0], Integer.parseInt(ipInfoArr[1]));  
        }  
        return map;  
    }  
  
    public String getClusterName() {  
        return clusterName;  
    }  
  
    public void setClusterName(String clusterName) {  
        this.clusterName = clusterName;  
    }  
  
    public String getNodeIpInfo() {  
        return nodeIpInfo;  
    }  
  
    public void setNodeIpInfo(String nodeIpInfo) {  
        this.nodeIpInfo = nodeIpInfo;  
    }  
  
} 



        //###  测试
	//根据指定的索引类型文档id  查询;我这里使用的Client 是TransportClient的父类;
	public static void searchSingle(Client client) {
		GetResponse gResponse = client.prepareGet("person","man", "1")
									  .execute()
									  .actionGet();
		logger.info("索引 {}" , gResponse.getIndex());    
        logger.info("类型 {}" , gResponse.getType());  
        logger.info("版本 {}" ,gResponse.getVersion()); 
        logger.info("是否成功 {}" , gResponse.isExists());  	
        Map results = gResponse.getSource(); 
        if(results != null) {  
            for(String key : results.keySet()) {  
                Object field = results.get(key);  
                System.out.println(key+"\t\t"+field);  
            }  
        } 
	}

 其它API的使用大家可到官网查看:官网

 ElasticSearch与SpringBoot的集成,大家可参考这篇博文:SpringBoot-Es


你可能感兴趣的:(elasticsearch)