1.版本问题
springboot中的springboot-data-elasticsearch内置了elasticsearch和client(highclient或者是lowclient),如果非要用springboot-data-elasticsearch去集成es那就选择好对应的版本,否则就自己引入依赖,我用的是spring2.1.6,elasticsearch7.3.2。
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.3.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.3.2</version>
<!--内置的elasticsearch版本低,故排除掉重新依赖-->
<exclusions>
<exclusion>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
</exclusion>
</exclusions>
</dependency>
配置类
/**
* ES数据源配置
* @author xuxiong
* 2020年7月17日 上午11:17:06
*/
@Configuration
public class ElasticsearchConfig {
@Autowired
private ElasticsearchDatasourceProperties elasticsearchDatasourceProperties;
@Bean
public RestHighLevelClient restHighLevelClient(){
String userName = elasticsearchDatasourceProperties.getUsername();
String password = elasticsearchDatasourceProperties.getPassword();
String[] esUrisAry = elasticsearchDatasourceProperties.getUris();
HttpHost[] httpHosts = new HttpHost[esUrisAry.length];
//将地址转换为http主机数组,未配置端口则采用默认9200端口,配置了端口则用配置的端口
for (int i = 0; i < httpHosts.length; i++) {
if (StringUtils.isNotBlank(esUrisAry[i])) {
esUrisAry[i] = esUrisAry[i].trim();
if (esUrisAry[i].contains(":")) {
String[] uris = esUrisAry[i].split(":");
httpHosts[i] = new HttpHost(uris[0], Integer.parseInt(uris[1]), "http");
} else {
httpHosts[i] = new HttpHost(esUrisAry[i], 9200, "http");
}
}
}
//如果未配置用户名,则进行无用户名密码连接,配置了用户名,则进行用户名密码连接
if (StringUtils.isBlank(userName)) {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(httpHosts));
return client;
} else {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(httpHosts).setHttpClientConfigCallback((httpClientBuilder) -> {
//这里可以设置一些参数,比如cookie存储、代理等等
httpClientBuilder.disableAuthCaching();
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
})
);
return client;
}
}
}
2.elasticsearch可以不用用户密码登陆也可以设置用户密码登录
在elasticsearch.yml中配置
#开启密码验证
xpack.security.enabled: true
xpack.security.transport.ssl.enabled: true
xpack.ml.enabled: true
#开启elasticsearch-head的访问
http.cors.enabled: true
http.cors.allow-origin: "*"
http.cors.allow-headers: Authorization,Content-Type,X-Requested-with,Content-Length
1、elasticsearch-7.3.2\bin 打开cmd窗口;
2、在cmd窗口输入:elasticsearch-setup-passwords interactive;
3、确认操作,设置密码;
如果只配置 http.cors.allow-headers: Authorization那么在登陆elasticsearch-head-master登陆是登不上的
设置密码后 http://127.0.0.1:9200/?auth_user=elastic&auth_password=密码
登陆head-master
暂时遇到这些,之后有再补充。