1 JAVA REST Client设置身份认证
通过RestHighLevelClient发送的es请求验证方式:文章来源:https://www.toymoban.com/news/detail-563973.html
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
/** 设置账号密码 */
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(ElasticsearchConstants.ELASTIC_USER_NAME, ElasticsearchConstants.ELASTIC_PASSWORD));
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost(ElasticsearchConstants.ELASTIC_SEARCH_HOST, ElasticsearchConstants.ELASTIC_SEARCH_PORT, "http"))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
})
);
2 HTTP Client设置身份认证
通过http直接发送的es请求认证方式:文章来源地址https://www.toymoban.com/news/detail-563973.html
CloseableHttpClient httpClient = HttpClients.createDefault();
//待连接的es-url
String url ="http://192.168.1.1:9200"
HttpPut httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(35000)
.setConnectionRequestTimeout(35000)
.setSocketTimeout(60000).build();
httpGet.setConfig(requestConfig);
//添加表头配置
httpGet.setHeader("Content-type", "application/json");
httpGet.setHeader("Accept", "application/json");
httpGet.setHeader("DataEncoding", "UTF-8");
// 加es身份认证
HttpHost targetHost = new HttpHost("192.168.1.1", 9200, "http");
/** 设置账号密码 */
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("es_user", "es_password"));
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
// Add AuthCache to the execution context
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credentialsProvider);
context.setAuthCache(authCache);
CloseableHttpResponse httpResponse = httpClient.execute(httpGet, context);
//获取连接状态码 (success:200;failed:401)
int statusCode = httpResponse.getStatusLine().getStatusCode()
//验证
if(statusCode == 200){
System.out.println("ES连接成功!")
}else{
System.out.println("ES连接失败!")
}
到了这里,关于ES的两种认证登录方式: JAVA REST Client/HTTP Client的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!