您好,登錄后才能下訂單哦!
本文小編為大家詳細介紹“ElasticSearch整合SpringBoot搭建配置的方法是什么”,內容詳細,步驟清晰,細節處理妥當,希望這篇“ElasticSearch整合SpringBoot搭建配置的方法是什么”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。
老規矩,先建maven
項目,下面是我的pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>springboot-es-all</artifactId> <version>1.0-SNAPSHOT</version> <properties> <java.version>1.8</java.version> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> </parent> <dependencies> <!--test--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <!--ElasticSearch 客戶端依賴--> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-client</artifactId> <version>7.8.0</version> </dependency> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>7.8.0</version> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.8.0</version> </dependency> <!--Hutool依賴--> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.4</version> </dependency> <!--fast-json--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.58</version> </dependency> <dependency> <groupId> org.slf4j </groupId> <artifactId> slf4j-api </artifactId> <version> 1.6.4 </version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.25</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.1.3.RELEASE</version> </plugin> </plugins> </build> </project>
這里我使用的是elasticsearch-rest-high-level-client
官方客戶端,建議大家盡量用官方的,因為隨著es
的不斷升級,很多api
都過時了,如果你使用spring-boot-starter-data-elasticsearch
這個要依賴社區去維護,很多新特性你沒法使用到,也會存在安全性問題。
啟動類:
@SpringBootApplication public class EsStudyApplication { public static void main(String[] args) { SpringApplication.run(EsStudyApplication.class, args); } }
配置文件 application.yml
:
server: port: 9000 elasticsearch: host: 0.0.0.0 port: 9200 username: password:
客戶端配置 config.EsClientConfig
:
@Configuration public class EsClientConfig { @Value("${elasticsearch.host}") private String host; @Value("${elasticsearch.port}") private int port; @Value("${elasticsearch.username}") private String userName; @Value("${elasticsearch.password}") private String password; @Bean public RestHighLevelClient restHighLevelClient() { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password)); RestHighLevelClient restHighLevelClient = new RestHighLevelClient( RestClient.builder(new HttpHost( host, port, "http")).setHttpClientConfigCallback(httpClientBuilder -> { httpClientBuilder.setMaxConnTotal(500); httpClientBuilder.setMaxConnPerRoute(300); return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); }) ); return restHighLevelClient; } }
然后客戶端我們就配好了,客戶端的配置其實還有很多,感興趣的同學自行查閱。后續使用的時候,直接導入RestHighLevelClient
實例就好了
接著啟動它,如果控制沒有報錯,說明配置沒啥問題了, 記得要開啟es
服務~
下面我們寫一點測試用例,來驗證我們是否可以操作es
,為了方便演示,這里直接使用SpringBootTest
來測試,大家平時在寫springboot
項目,類測試的時候也可以這么做
新建api.IndexApi
,調用ping()
方法來測試是否鏈接成功:
@Slf4j @SpringBootTest public class IndexApi { /** * es 索引 */ public static final String index = "study"; @Autowired private RestHighLevelClient client; @Test public void ping() throws IOException { if(client.ping(RequestOptions.DEFAULT)) { log.info("鏈接成功"); }else { log.info("鏈接失敗 !"); } } }
點擊IndexApi
左上角的綠色箭頭啟動測試用例, 如果報錯,嘗試添加以下 注解
@RunWith(SpringRunner.class) @SpringBootTest(classes = { EsStudyApplication.class }) public class IndexApi {....}
返回:
鏈接成功
說明客戶端
與es
服務端是通的
通過前面的學習,有了一定的基礎之后,回到代碼中其實就是調調方法
,因為你知道了這個代碼的邏輯做了什么操作。下面來看下如何創建索引:
/** * 創建索引 */ @Test public void createIndex() throws IOException { CreateIndexRequest request = new CreateIndexRequest(index); CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT); log.info("創建索引 ===> "+ JSONObject.toJSONString(createIndexResponse)); // 創建索引 ===> {"acknowledged":true,"fragment":false,"shardsAcknowledged":true} }
大家可以返回到kibana
中查看索引
是否被創建,從而驗證代碼執行是否成功
添加別名:
// alias request.alias(new Alias("study_alias"));
索引設置settings
:
// index settings request.settings( Settings.builder() .put("index.number_of_shards", 3) .put("index.number_of_replicas", 2) );
索引映射mapping
:
// index mappings // { // "mapping": { // "_doc": { // "properties": { // "name": { // "type": "text" // } // } // } // } // } XContentBuilder builder = XContentFactory.jsonBuilder(); builder.startObject(); { builder.startObject("properties"); { builder.startObject("name"); { builder.field("type", "text"); } builder.endObject(); } builder.endObject(); } builder.endObject(); request.mapping(builder);
設置請求超時時間:
// 請求設置 request.setTimeout(TimeValue.timeValueMinutes(1));
/** * 判斷索引是否存在 * @throws IOException */ @Test public void existIndex() throws IOException { GetIndexRequest request = new GetIndexRequest(index); boolean exists = client.indices().exists(request, RequestOptions.DEFAULT); log.info("索引{}存在 ===> {}", index, exists); }
/** * 刪除索引 * @throws IOException */ @Test public void delIndex() throws IOException { DeleteIndexRequest request = new DeleteIndexRequest(index); AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT); log.info("刪除索引 ===> {}", JSONObject.toJSONString(delete)); // 刪除索引 ===> {"acknowledged":true,"fragment":false} }
讀到這里,這篇“ElasticSearch整合SpringBoot搭建配置的方法是什么”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。