Elasticsearch Java API 的使用(10)—在Spring框架中建立持久化连接

时间:2022-10-14 21:53:58

1、问题

后台跟Elasticsearch打交道需要建立起起客户端的连接,才能对Elasticsearch进行读写操作,频繁的建立连接、断开,将降低Elasticsearch的工作效率;建立持久化将减少后台与Elasticsearch建立客户端连接的时间,大大提高工作效率。
通过Spring的配置文件将Elasticsearch以注入的方式建立持久化的连接将可以解决这个问题。

2、解决:

A、配置Spring文件
<!-- 数据仓库连接器 -->
<bean id="dwClient" class="com.ygsoft.apm.support.ElasticSearchClientFactoryBean">
<property name="clusterName">
<value>${dw.elasticsearch.clusterName}</value>
</property>
<property name="host">
<value>${dw.elasticsearch.host}</value>
</property>
<property name="port">
<value>${dw.elasticsearch.port}</value>
</property>
</bean>
B、创建ElasticSearchClientFactoryBean.java
package com.ygsoft.apm.support;

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

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.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.FactoryBean;

/**
* 功能描述:ElasticSearchClientFactoryBean
* 作者:***
* 创建时间:****年**月**日
* 修改时间:
* *******有限公司
*/

public class ElasticSearchClientFactoryBean implements FactoryBean<Client>{

private String clusterName = "elasticsearch";
private String host = "10.121.8.3";
private Integer port = 9300;

@SuppressWarnings("resource")
@Override
public Client getObject() throws Exception {
try {
//设置集群名称
Settings settings = Settings.builder()
.put("cluster.name", clusterName)
.build();
//创建client
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
return client;
} catch (UnknownHostException e) {
e.printStackTrace();
}

return null;
}

@Override
public Class<?> getObjectType() {
return Client.class;
}

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

public String getClusterName() {
return clusterName;
}

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

public String getHost() {
return host;
}

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

public Integer getPort() {
return port;
}

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

注:clusterName、host、port这三个参数可以通过.properties配置文件中获取,以方便部署。

C、在使用的方法中注入
@RestController
@RequestMapping({"/api/xxxxx"})
public class xxxxxController
{

@Autowired
private Client client;

.......
}