Spring 整合 ElasticSearch
补充知识 Elasticsearch 与 MySQL 数据同步的方法,具体方案选型参考:Elasticsearch 存储设计与MySQL数据同步方案 这个 Spring Data ES 的使用参考自 通过Spring Data Elasticsearch操作ES
总之现在依赖的工具:
- SpringBoot
- Elasticsearch
- MySQL
- 阿里的 Canal
Spring 的 ES 客户端们
<!-- https://mvnrepository.com/arti ... /rest -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>rest</artifactId>
</dependency>
<!-- https://mvnrepository.com/arti ... earch -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
</dependency>
<!-- https://mvnrepository.com/arti ... lient -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
</dependency>
首先:Spring 简单整合 ES
首先来看下 SpringBoot 如何整合 ES,首先修改下 ES 的配置文件,配置一下跨域
http.cors.enabled: true
http.cors.allow-origin: "*"
然后 Docker 重启下 ES
Spring Boot 引入 ES,注意,得先检查下版本,不清楚使用什么版本参考 这个网站
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
配置 application.yml:
spring:
application:
name: map-service-search
elasticsearch:
rest:
uris: http://localhost:19200
password:
username:
read-timeout: 1m
connection-timeout: 1s
注意:也可以不配这个,自己手动创建 Bean 配置(具体看原文)
配置好后测试创建一个 index
@SpringBootApplication
public class SearchApplication {
public static void main(String[] args) {
SpringApplication.run(SearchApplication.class, args);
}
/**
* 创建一个 index(对应关系型数据库的库)
*/
@Bean
public boolean createTestIndex(RestHighLevelClient restHighLevelClient) throws Exception {
try {
// 如果存在则先删除 "hello-world" 如果不存在会抛出错误,这里不处理就行了
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("hello-world");
restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT); // 1
} catch (Exception ignored) {
}
// 导入的是 org.elasticsearch.client.indices.CreateIndexRequest
CreateIndexRequest createIndexRequest = new CreateIndexRequest("hello-world");
createIndexRequest.settings(
Settings.builder()
.put("index.number_of_shards", 1) // 分片数(默认 5)
.put("index.number_of_replicas", 0)); // 备份分片数目(默认 1)
restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT); // 2
return true;
}
}
检查是否创建成功
http://localhost:19200/_cat/indices?v

可以看到已经注册成功了