基于elastic 7.1.1的版本的java实现
/**
* 获取elasticsearch 客户端 client
*
* @return
*/
public RestHighLevelClient getClient() {
if (client == null) {
// 构建客户端Client
try {
/** 用户认证对象 */
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
/** 设置账号密码 */
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(ES_USERNAME, ES_PASSWORD));
/** 创建rest client对象 */
client = new RestHighLevelClient(
RestClient.builder(new HttpHost(ES_HOST, ES_PORT, "http"))
.setRequestConfigCallback(requestConfigBuilder -> {
return requestConfigBuilder
.setConnectTimeout(10000) //连接超时(默认为1秒)
.setSocketTimeout(60000);//套接字超时(默认为30秒)
}
).setHttpClientConfigCallback(httpClientBuilder -> {
return httpClientBuilder
.setDefaultCredentialsProvider(credentialsProvider)
.setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(1).build());//线程数
}
));
} catch (Exception e) {
logger.error("build Elastic client error !", e);
}
}
return client;
}
基于elastic 2.4.1版本的java实现
需要依赖X-Plugins: Shield文章来源地址https://www.toymoban.com/news/detail-573417.html
public Client getClient() {
if (client == null) {
// 设置集群名称
Settings settings = addClusterName();
// 构建客户端Client
try {
this.client = getConnectToCluster(settings);
} catch (Exception e) {
logger.error("build Elastic client error !", e);
}
}
return client;
}
/**
* @Description: 设置集群名称
* @param:
* @return: void
* @throws @since JDK 1.6
*/
private Settings addClusterName() {
// 设置集群名称,不设置默认是:elasticsearch
// 设置client.transport.sniff为true来使客户端去嗅探整个集群的状态,把集群中其它机器的ip地址加到客户端中
// 这样做的好处是一般你不用手动设置集群里所有集群的ip到连接客户端,它会自动帮你添加,并且自动发现新加入集群的机器
return Settings.settingsBuilder().put("shield.user",esusername+":"+esuserpassword).build();
}
/**
* @Description: 构建客户端连接
* @param: @param settings
* @param: @return
* @return: TransportClient
* @throws @since JDK 1.6
*/
private Client getConnectToCluster(Settings settings) {
Client client = TransportClient.builder()
.addPlugin(ShieldPlugin.class)
.settings(settings).build()
.addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress(elas_host, elas_port)));
return client;
}
文章来源:https://www.toymoban.com/news/detail-573417.html
到了这里,关于java代码实现用户名密码连接 es7.1.1的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!