1、9300:TCP
spring-data-elasticsearch:transport-api.jar;
2、9200:HTTP
JestClient:非官方,更新慢
RestTemplate:模拟发 HTTP 请求,ES 很多操作需要自己封装,麻烦
HttpClient:同上
Elasticsearch-Rest-Client:官方 RestClient,封装了 ES 操作,API 层次分明,上手简单最终选择
Elasticsearch-Rest-Client(elasticsearch-rest-high-level-client)https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high.html
创建一个模块。。
只选择 web 即可
导入依赖
将服务加入到注册中心
在 config 包下新建 ElasticSearchConfig 配置文件
package com.fancy.gulimall.search.config;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ElasticSearchConfig {
@Bean
public RestHighLevelClient esRestClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("192.168.38.130", 9200, "http")
)
);
return client;
}
}
参照官方文档:
@Test
void test1() throws IOException {
Product product = new Product();
product.setSpuName("华为");
product.setId(10L);
IndexRequest request = new IndexRequest("product").id("20").source("spuName","华为","id",20L);
try {
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
System.out.println(request.toString());
IndexResponse response2 = client.index(request, RequestOptions.DEFAULT);
} catch (ElasticsearchException e) {
if (e.status() == RestStatus.CONFLICT) {}
}
}
阿里云搭建好的架构: