1、SpringBoot 版本 : 2.7.14
org.springframework.boot
spring-boot-starter-parent
2.7.14
2、ElasticSearch版本 : 7.9.1
<properties>
<java.version>1.8java.version>
<elasticsearch.version>7.9.1elasticsearch.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-configuration-processorartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-elasticsearchartifactId>
dependency>
dependencies>
在application.yaml中添加如下数据
es:
clusterName: clusterTestEs # es集群的名称
userName: userName # es集群的访问用户名
passWord: password # es集群的访问密码
nodes: # es集群的节点列表
- 192.168.2.5:9200
- 192.168.2.6:9200
- 192.168.2.7:9200
通过配置类的方式读取application.yaml中的属性
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.List;
@Configuration
@ConfigurationProperties(prefix = "es") // 指定配置的前缀
public class ElasticSearchProperties {
private String clusterName;
private String userName;
private String passWord;
private List<String> nodes;
// 下面是正常的 无参构造、有参构造、getter方法、setter方法、toString() 方法
。。。。。。
}
主要是创建一个RestHighLevelClient 类型的客户端对象,在实际操作过程中都要用到这个对象。
下面的这个方法,直接照抄即可,无需进行修改。
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.Node;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;
import java.util.Objects;
@Configuration
public class ElasticSearchConfig {
private Logger logger = LoggerFactory.getLogger(ElasticSearchConfig.class);
private static final int ADDRESS_LENGTH = 2;
private static final String HTTP_SCHEME = "http";
@Autowired
private ElasticSearchProperties esProperties;
@Bean
public RestClientBuilder restClientBuilder() {
List<String> nodes = esProperties.getNodes();
HttpHost[] httpHosts = nodes.stream()
.map(this::makeHttpHost)
.filter(Objects::nonNull)
.toArray(HttpHost[]::new);
return RestClient.builder(httpHosts);
}
/**
* 下面的这个bean 是一个创建客户端的核心的 bean
*/
@Bean(name = "highLevelClient")
public RestHighLevelClient highLevelClient(@Autowired RestClientBuilder restClientBuilder){
//配置身份验证 : 就是用户名密码
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(esProperties.getUserName(), esProperties.getPassWord()));
restClientBuilder.setHttpClientConfigCallback(
httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider).disableAuthCaching());
//设置连接超时和套接字超时
restClientBuilder.setRequestConfigCallback(
requestConfigBuilder -> requestConfigBuilder.setSocketTimeout(10000).setConnectTimeout(60000));
//设置监听器,每次节点失败都可以监听到,可以作额外处理
restClientBuilder.setFailureListener(new RestClient.FailureListener() {
@Override
public void onFailure(Node node) {
super.onFailure(node);
logger.error(node.getHost() + "--->该节点失败了");
}
});
// 返回客户端对象
return new RestHighLevelClient(restClientBuilder);
}
// 处理节点的方法,把配置文件的节点的IP和端口号拆分开,创建HttpHost对象
private HttpHost makeHttpHost(String str) {
assert StringUtils.isNotEmpty(str);
String[] address = str.split(":");
if (address.length == ADDRESS_LENGTH) {
String ip = address[0];
int port = Integer.parseInt(address[1]);
logger.info("ES连接ip和port:{},{}", ip, port);
return new HttpHost(ip, port, HTTP_SCHEME);
} else {
logger.error("传入的ip参数不正确!");
return null;
}
}
}
经过以上5个步骤,已经成功配置并且获取到了操作elasticsearch的客户端对象,
下面就可以使用该客户端对象进行操作了。
因此,可以使用该对象进行一些常用方法的封装,下面的代码以判断索引库是否存在为例,进行演示。
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class ElasticSearchUtil {
@Qualifier("highLevelClient")
@Autowired
private RestHighLevelClient rhlClient;
private static RestHighLevelClient client;
/**
* spring容器初始化的时候执行该方法
*/
@PostConstruct
public void init() {
client = this.rhlClient;
log.info("esclient 对象初始化success!{}",client);
}
/**
* 判断索引是否存在
* @param indexName
* @throws Exception
*/
public void judgeIndexExist(String indexName) throws Exception{
GetIndexRequest getIndexRequest = new GetIndexRequest(indexName);
boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
System.out.println(indexName + " exists ? : " + exists);
}
}
测试思路 :
1.在spring boot中编写一个简单的接口,接口中节点调用一下 步骤6中的方法。
2.访问接口看是否能够正常获取到状态即可。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class EsController {
@Autowired
private ElasticSearchUtil elasticSearchUtil;
@PostMapping("/judgeIndexState")
public String createIndex(@RequestBody String indexName){
logger.info("参数索引名称是 : "+indexName);
try {
// 直接调用工具方法中的参数即可
elasticSearchUtil.judgeIndexExist(indexName);
}catch (Exception e){
e.printStackTrace();
}
return "-"+indexName;
}
}
在步骤7中访问成功后,即表示当前的集成工作完成。