参考文档:es 集群可视化界面详细讲解
下载地址:https://www.elastic.co/cn/downloads/elasticsearch
1.1 选择版本
1.2 下载
1.3 修改配置文件:
在config目录下打开elasticsearch.yml修改配置文件
设置ip端口:也可直接将配置文件中的注释去掉,在做修改
#设置ip、端口
network.host: 127.0.0.1
http.port: 19200
解决跨域:
#跨域
http.cors.enabled: true
http.cors.allow-origin: "*"
设置需要通过账号密码访问elasticsearch6.8.0:添加以下配置之后,Java连接es的时候需要添加用户名和密码
#开启权限特性
xpack.security.enabled: true
xpack.license.self_generated.type: basic
xpack.security.transport.ssl.enabled: true
Elasticsearch 的默认账户为 elastic 默认密码为 changme
如果需要修改账户密码:可参考
1.3.1:ElasticSearch设置用户名密码访问
1.4 启动 elasticsearch6.8.0
下载完成之后解压安装包到相应目录下,在bin目录下打开elasticsearch.bat 即可启动
2.1 引入依赖
org.elasticsearch.client
elasticsearch-rest-high-level-client
6.8.0
org.elasticsearch.client
elasticsearch-rest-client
org.elasticsearch
elasticsearch
org.elasticsearch
elasticsearch
6.8.0
org.elasticsearch.client
elasticsearch-rest-client
6.8.0
2.2 在application.yml文件中添加配置
elastic:
host: ${ELASTIC_HOST:localhost}
port: ${ELASTIC_PORT:19200}
user: ${ELASTIC_USER:elastic}
pass: ${ELASTIC_PASS:123456}
2.3 创建配置类
package com.lcm.web.config;
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.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SystemConfiguration {
@Value("${elastic.host}")
private String esHost;
@Value("${elastic.port}")
private int esPort;
@Value("${elastic.user}")
private String esUser;
@Value("${elastic.pass}")
private String esPass;
@Bean
public RestHighLevelClient initRestHighLevelClient() {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
//需要用户名和密码的认证
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(esUser, esPass));
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost(esHost, esPort, "http")).setHttpClientConfigCallback(httpClientBuilder -> {
httpClientBuilder.disableAuthCaching();
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}));
return client;
}
}
2.4 说明
完成以上步骤后,在启动项目之后,springboot会自动加载配置类里面的配置链接es,当我们在其他类中需要操作es时,可通过以下方式注入es官网推荐的es客户端组件RestHighLevelClient:
@Autowired
private RestHighLevelClient restHighLevelClient;
使用方式及API可查看官方文档