开发环境和正式环境共用一个Elasticsearch,spring boot如何配置

**场景:** 最近做了一个系统,使用Elasticsearch做了全文搜索,系统分为开发环境和正式环境,正式环境供公司内部使用,因为服务器资源不太充裕,决定开发环境和正式环境共用一个Elasticsearch,不同环境仅以索引名称(indexName)进行区分。即:一个Elasticsearch供两个系统使用。 **实现:** 1.在配置文件里定义索引名称 开发环境的配置:application-dev.yml ```yml spring: data: elasticsearch: repositories: enabled: true cluster-nodes: 172.16.11.109:9300 cluster-name: elasticsearch article-index-name: article ``` 正式环境的配置:application-prod.yml ```yml spring: data: elasticsearch: repositories: enabled: true cluster-nodes: 172.16.11.109:9300 cluster-name: elasticsearch article-index-name: article-prod ``` 通过以上配置文件可以看出,两个环境只有索引名称是不一样的(索引名称article-index-name,属于自己定义的配置项,这里为了便于统一管理,将其与Elasticsearch的配置放在一起)。 2.编写一个配置类,用于读取配置文件中索引名称的值 ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ArticleIndexConfig{ @Value("${spring.data.elasticsearch.article-index-name}") private String articleIndexName; @Bean public String articleIndexName(){ return articleIndexName; } } ``` 3.在Elasticsearch的实体类的注解上使用 ```java import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; import java.io.Serializable; @Document(indexName = "#{@articleIndexName}", type = "java") public class ArticleModel implements Serializable{ private static final long seriaVersionUID = 6320548148250372656L; @Id private String rowId; @Field(type = FieldType.text) private String title; @Field(type = FieldType.text) private String content; //getter和setter省略 //... } ``` 4.经过以上的动作,两个环境(开发环境和正式环境)就可以共用一个Elasticsearch,而且相互之间的数据是隔离开的,互不影响。