本人在学习elasticsearch8.0时,因elasticsearch8.0缺少java文档,自己在摸索中学习es8.0 java。
首先在es官网下载8.0,安装后,使用java调用es报错连接超时,es中提示
received plaintext http traffic on an https channel, closing connection Netty4HttpChannel
解决方法 因es8.0在安装时默认开启了SSL认证,在es安装根目录config/elasticsearch.yml文件修改
# Enable encryption for HTTP API client connections, such as Kibana, Logstash, and Agents
xpack.security.http.ssl:
enabled: false
keystore.path: certs/http.p12
将enabled改为false
在改好yml启动后,在使用官网
https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/8.0/connecting.html
提供的连接demo连接时异常,后来测试好像改完yml异常就消失了,不知道什么原因
RestClient restClient = RestClient.builder(
new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
在没测试之前使用
private static final String clusterNodes = "127.0.0.1:9200";//es集群节点
//用户名
private static final String account = "elastic";
//密码
private static final String passWord = "cs8I7+dQjh1BGwUaO_KM";
public static ElasticsearchClient client;
public static RestClientBuilder builder;
public static RestClient restClient;
public static ElasticsearchTransport transport;
//有密码登录
public static void main(String[] args) {
try {
HttpHost[] httpHosts = Arrays.stream(clusterNodes.split(",")).map(x -> {
String[] hostInfo = x.split(":");
return new HttpHost(hostInfo[0], Integer.parseInt(hostInfo[1]));
}).toArray(HttpHost[]::new);
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
//设置账号密码
credentialsProvider.setCredentials(
AuthScope.ANY, new UsernamePasswordCredentials(account, passWord));
builder = RestClient.builder(httpHosts)
.setHttpClientConfigCallback(httpClientBuilder ->
httpClientBuilder
.setDefaultCredentialsProvider(credentialsProvider));
// Create the low-level client
restClient = builder.build();
// Create the transport with a Jackson mapper
transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());
// And create the API client
client = new ElasticsearchClient(transport);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
client.shutdown();
transport.close();
restClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
连接测试无问题
//创建索引并返回状态
Boolean acknowledged = client.indices().create(c -> c.index("user")).acknowledged();
GetIndexResponse getIndexResponse = client.indices().get(c -> c.index("user"));
DeleteIndexResponse deleteIndexResponse = client.indices().delete(c -> c.index("user"));
User user = new User("zhangsan", 18, "男");
String userJson = new Gson().toJson(user);
IndexResponse indexResponse = client.index(IndexRequest.of(x -> {
x.id("10001");
x.index("user");
x.document(user);
return x;
}));
以上方法不确定是否正确,本人自己测试无问题,文档中没有找到相应写法,如有问题,请大佬指正
下一篇链接: https://blog.csdn.net/u013979493/article/details/123172320?utm_source=app&app_version=5.0.1&code=app_1562916241&uLinkId=usr1mkqgl919blen