接第23節(jié)
五、Elasticsearch-Rest-Client
Java 操作 ES 的兩種方式:
1) 、9300:TCP (我們不在9300操作,官方也不建議)
-
spring-data-elasticsearch:transport-api.jar;- springboot 版本不同,transport-api.jar不同,不能適配es版本
- 7.x 已經(jīng)不建議使用,8 以后就要廢棄
2)、9200:HTTP(推薦使用)
-
JestClient:非官方,更新慢 -
RestTemplate:模擬發(fā) HTTP 請(qǐng)求,ES 很多操作需要自己封裝,麻煩 -
HttpClient:同上 I -
Elasticsearch-Rest-Client:官方 RestClient,封裝了 ES 操作, API 層次分明,上手簡(jiǎn)單最終選擇
Elasticsearch-Rest-Client(elasticsearch-rest-high-level-client)
在這里插入圖片描述
在這里插入圖片描述
1、SpringBoot整合
1)在pafcmall項(xiàng)目中新添加一個(gè)模塊pafcmall-search,當(dāng)然你也可以,單獨(dú)創(chuàng)建一個(gè)項(xiàng)目
在這里插入圖片描述
使用 spring 啟動(dòng)器創(chuàng)建:
在這里插入圖片描述
添加
group 和 artifact 信息:在這里插入圖片描述
添加
web 依賴:在這里插入圖片描述
2)、修改pom文件
添加對(duì)應(yīng)的當(dāng)前 ES 版本的 rest-high-level-client 依賴,我使用的是7.4.2,所以添加7.4.2的依賴
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.4.2</version>
</dependency>
在這里插入圖片描述
可以看到當(dāng)前
SpingBoot(2.2.6)版本默認(rèn)管理的 ES 的版本和 elasticsearch-rest-high-level-client 的版本不一致:在這里插入圖片描述
需要修改一下
pom 文件,讓 ES 和 elasticsearch-rest-high-level-client 的版本保持一致:
<elasticsearch.version>7.4.2</elasticsearch.version>
在這里插入圖片描述
3)、添加 ES 配置類
/**
* @description: Elasticsearch 配置文件
* <p>
* SpringBoot 集成 ES 的步驟:
* 1、導(dǎo)入依賴
* https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-getting-started-maven.html
* 2、編寫 ES 配置,給容器中注入一個(gè) RestHighLevelClient,用來操作 9200 端口
* https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-getting-started-initialization.html
* 3、參照官方API
*/
@Configuration
public class PafcmallElasticsearchConfig {
@Bean
public RestHighLevelClient esRestHighLevelClient() {
RestHighLevelClient client = new RestHighLevelClient(
// 這里可以配置多個(gè) es服務(wù),我當(dāng)前服務(wù)不是集群,所以目前只配置一個(gè)
RestClient.builder(
new HttpHost("192.168.50.10", 9200, "http")));
return client;
}
}
在這里插入圖片描述
修改啟動(dòng)類:
@EnableDiscoveryClient // 開啟服務(wù)注冊(cè)與發(fā)現(xiàn)
// 這里需要排除一下數(shù)據(jù)庫的依賴,因?yàn)橐肓藀afcmall-common依賴,其中包含了mybatis-plus的配置,目前我們的服務(wù)還沒有依賴數(shù)據(jù)源,所以需要排除
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class PafcmallSearchApplication {
public static void main(String[] args) {
SpringApplication.run(PafcmallSearchApplication.class, args);
}
}
修改 application.properties 文件:
# nacos配置中心地址
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
# 配置應(yīng)用名
spring.application.name=pafcmall-search
使用測(cè)試類測(cè)試:
@SpringBootTest
class PafcmallSearchApplicationTests {
@Autowired
private RestHighLevelClient client;
@Test
void contextLoads() {
System.out.println(client);
}
}

在這里插入圖片描述
更多整合信息請(qǐng)參考 java-rest-high-getting-started-maven 和 java-rest-high-getting-started-initialization
參考: