目录
项目环境:
- jdk 1.8
- spring boot 1.5.1
由于spring boot 目前SpringBoot 1.5.1.RELEASE和Spring Data Elasticsearch 2.10.RELEASE仅支持ElasticSearch 2.4.0。 他们不支持最新版本的ElasticSearch 5.x版本。
Spring Boot Version (x) | Spring Data Elasticsearch Version (y) | Elasticsearch Version (z) |
---|---|---|
x <= 1.3.5 | y <= 1.3.4 | z <= 1.7.2* |
x >= 1.4.x | 2.0.0 <=y < 5.0.0** | 2.0.0 <= z < 5.0.0** |
mavan 配置 pom.xml
<!-- add the elasticsearch repo -->
<repositories>
<repository>
<id>elasticsearch-releases</id>
<url>https://artifacts.elastic.co/maven</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<!-- 版本控制 -->
<properties>
<log4j-api.version>2.8.2</log4j-api.version>
<log4j-core.version>2.8.2</log4j-core.version>
<elasticsearch.version>5.5.3</elasticsearch.version>
<transport.version>5.5.3</transport.version>
<!-- x-pack-transpor 版本控制 start -->
<x-pack-transport.version>5.5.3</x-pack-transport.version>
<!-- x-pack-transpor 版本控制 end -->
</properties>
<!-- elasticsearch 5.x 依赖 -->
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j-api.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j-core.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>${transport.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<!-- x-pack-transpor 版本控制 start -->
<artifactId>x-pack-transport</artifactId>
<version>${x-pack-transport.version}</version>
<!-- x-pack-transpor 版本控制 end -->
</dependency>
</dependencies>
: 特注
ElasticSearch 5.x 根据官网配置maven 依赖, 由于 5.0x的 jar 内部使用的 apache log4日志。
所以要配置额外的依赖支持 org.apache.logging.log4j。
application-dev.yml
spring:
data:
elasticsearch:
cluster-name: es-cn
cluster-nodes: es-cn.elasticsearch.aliyuncs.com:9300
username-password: elastic:O9VV8MaBmflV9g
properties:
transport.tcp.connect_timeout: 40s
client.transport.ping_timeout: 10s
client.transport.nodes_sampler_interval: 5s
配置 java Client连接池
package com.****.****.config;
import com.****.****.common.utils.StringUtils;
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.elasticsearch.xpack.client.PreBuiltXPackTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
*TransportClientFactoryBean
*
*@author liuf
*/
@Configuration
public class ElasticsearchConfiguration implements FactoryBean<TransportClient>, InitializingBean, DisposableBean {
private static final Logger logger = LoggerFactory.getLogger(ElasticsearchConfiguration.class);
@Value("${spring.data.elasticsearch.cluster-nodes}")
private String clusterNodes ;
@Value("${spring.data.elasticsearch.cluster-name}")
private String clusterName;
@Value("${spring.data.elasticsearch.username-password}")
private String usernamePassword;
/**
* 超时时间
*/
@Value("${spring.data.elasticsearch.properties.transport.tcp.connect_timeout}")
private String connectTimeout;
/**
* 等待来自节点的ping响应的时间。默认值为5s。
*/
@Value("${spring.data.elasticsearch.properties.client.transport.ping_timeout}")
private String pingTimeout;
/**
* 采样/ ping列出和连接的节点的频率。默认值为5s
*/
@Value("${spring.data.elasticsearch.properties.client.transport.nodes_sampler_interval}")
private String nodesSamplerInterval;
private TransportClient client;
@Override
public void destroy() throws Exception {
try {
logger.info("Closing elasticSearch client");
if (client != null) {
client.close();
}
} catch (final Exception e) {
logger.error("Error closing ElasticSearch client: ", e);
}
}
@Override
public TransportClient getObject() throws Exception {
return client;
}
@Override
public Class<TransportClient> getObjectType() {
return TransportClient.class;
}
@Override
public boolean isSingleton() {
return false;
}
@Override
public void afterPropertiesSet() throws Exception {
buildClient();
}
protected void buildClient() {
try {
//x-pack权限方法
if (StringUtils.isNotBlank(usernamePassword)) {
PreBuiltXPackTransportClient preBuiltTransportClient = new PreBuiltXPackTransportClient(settings());
if (!"".equals(clusterNodes)) {
for (String nodes : clusterNodes.split(",")) {
String InetSocket[] = nodes.split(":");
String Address = InetSocket[0];
Integer port = Integer.valueOf(InetSocket[1]);
preBuiltTransportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(Address), port));
}
client = preBuiltTransportClient;
// client.threadPool().getThreadContext().putHeader("Authorization", "Basic "+ Encodes.decodeBase64(usernamePassword));
}
} else {
//没有x-pack权限访问
PreBuiltTransportClient preBuiltTransportClient = new PreBuiltTransportClient(settings());
if (!"".equals(clusterNodes)) {
for (String nodes:clusterNodes.split(",")) {
String InetSocket [] = nodes.split(":");
String Address = InetSocket[0];
Integer port = Integer.valueOf(InetSocket[1]);
preBuiltTransportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(Address),port ));
}
client = preBuiltTransportClient;
}
}
} catch (UnknownHostException e) {
logger.error(e.getMessage());
}
}
private Settings settings(){
Settings.Builder settings = Settings.builder();
settings.put("cluster.name",clusterName)
// .put("client.transport.ignore_cluster_name", false)
// .put("client.transport.sniff", true)
// .put("xpack.security.transport.ssl.enabled", true)
.put("client.transport.nodes_sampler_interval", nodesSamplerInterval) // elasticSearch 健康检查时间
.put("transport.tcp.connect_timeout", connectTimeout) // elasticSearch 超时时间
.put("client.transport.ping_timeout",pingTimeout); //elasticSearch ping
//x-pack权限方法
if (StringUtils.isNotBlank(usernamePassword)) {
settings.put("xpack.security.user", usernamePassword);
} else {
}
return settings.build();
}
}
参考文献
[1] : 参考模版