接第23節
五、Elasticsearch-Rest-Client
Java 操作 ES 的兩種方式:
1) 、9300:TCP
(我們不在9300操作,官方也不建議)
-
spring-data-elasticsearch:transport-api.jar
;- springboot 版本不同,transport-api.jar不同,不能適配es版本
- 7.x 已經不建議使用,8 以后就要廢棄
2)、9200:HTTP
(推薦使用)
-
JestClient
:非官方,更新慢 -
RestTemplate
:模擬發 HTTP 請求,ES 很多操作需要自己封裝,麻煩 -
HttpClient
:同上 I -
Elasticsearch-Rest-Client
:官方 RestClient,封裝了 ES 操作, API 層次分明,上手簡單最終選擇
Elasticsearch-Rest-Client(elasticsearch-rest-high-level-client
)
在這里插入圖片描述
在這里插入圖片描述
1、SpringBoot整合
1)在pafcmall
項目中新添加一個模塊pafcmall-search
,當然你也可以,單獨創建一個項目
在這里插入圖片描述
使用 spring 啟動器創建:
在這里插入圖片描述
添加
group
和 artifact
信息:在這里插入圖片描述
添加
web
依賴:在這里插入圖片描述
2)、修改pom
文件
添加對應的當前 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>
在這里插入圖片描述
可以看到當前
SpingBoot(2.2.6)
版本默認管理的 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、導入依賴
* https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-getting-started-maven.html
* 2、編寫 ES 配置,給容器中注入一個 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(
// 這里可以配置多個 es服務,我當前服務不是集群,所以目前只配置一個
RestClient.builder(
new HttpHost("192.168.50.10", 9200, "http")));
return client;
}
}
在這里插入圖片描述
修改啟動類
:
@EnableDiscoveryClient // 開啟服務注冊與發現
// 這里需要排除一下數據庫的依賴,因為引入了pafcmall-common依賴,其中包含了mybatis-plus的配置,目前我們的服務還沒有依賴數據源,所以需要排除
@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
# 配置應用名
spring.application.name=pafcmall-search
使用測試類測試:
@SpringBootTest
class PafcmallSearchApplicationTests {
@Autowired
private RestHighLevelClient client;
@Test
void contextLoads() {
System.out.println(client);
}
}
在這里插入圖片描述
更多整合信息請參考 java-rest-high-getting-started-maven 和 java-rest-high-getting-started-initialization
參考: