我们可以为ElasticSearch服务,添加我们的
用
户
名
以
及
密
码
\color{red}{用户名以及密码}
用户名以及密码进行权限验证。那么我们就需要在我们的代码中进行授权,不然就会提示提示No Authentication
的错误信息。
1.Spring Boot与ElasticSearch结合
当使用ElasticSearch和Spring Boot相结合的时候,我们可以在application.yaml
配置文件中,加入下面的属性为其添加用户名以及密码验证。代码无需进行任何改动即可完成授权工作。
spring:
elasticsearch:
rest:
username: elastic
password: elastic
2.单独使用ElasticSearch进行授权
- 首先在pom.xml文件中添加
ElasticSearch
的依赖文件:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.8.1</version>
</dependency>
- 在ElasticSearch无需授权的时候:
我们可以使用ElasticSearch High Level创建一个客户端对象,完成后续向ElasticSearch服务发送请求:
RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
RestHighLevelClient client = new RestHighLevelClient(builder);
注意:ElasticSearch High Level的文档中 并 没 有 \color{red}{并没有} 并没有提及如何进行登录验证操作,文档而是在Low Level Basic Authentication的进行了说明。
- 在ELasticSearch需要权限验证:
我们可以在构建RestClient.builder
方法的时候,提供一个HttpClientConfigCallback
接口实例为ElasticSearch配置基本的授权信息。通过setHttpClientConfigCallback
方法设置HttpClientConfigCallBack
实例,代码如下:
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
// 设置用户名以及密码
UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials("elastic", "elastic");
credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"))
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
RestHighLevelClient client = new RestHighLevelClient(builder);
注意:第二步和第三步使用 其 中 一 个 \color{red}{其中一个} 其中一个就可以了。第二步表示没有授权的时候,连接ElasticSearch服务的方法,而第三步表示ElasticSearch有授权时候,连接ElasticSearch服务的方法。
剩下的工作就和没有授权的时候一样了。例如搜索的时候,创建一个SearchRequest
对象,添加数据的时候,创建一个IndexRequest
对象。等等操作
更多精彩内容:请关注公众号: