java - Spring Boot Elasticsearch 配置

标签 java spring-boot elasticsearch

我有一个工作的 Spring Boot Elasticsearch 应用程序,它使用两个配置文件之一:application.dev.properties 或 application.prod.properties。那部分工作正常。我在让外部 elasticsearch 从 application.xxx.properties 中读取时遇到问题。

这个有效:

@Configuration
@PropertySource(value = "classpath:config/elasticsearch.properties")
public class ElasticsearchConfiguration {

    @Resource
    private Environment environment;

    @Bean
    public Client client() {
        TransportClient client = new TransportClient();
        TransportAddress address = new InetSocketTransportAddress(
                environment.getProperty("elasticsearch.host"), 
                Integer.parseInt(environment.getProperty("elasticsearch.port"))
        );
        client.addTransportAddress(address);        
        return client;
    }

    @Bean
    public ElasticsearchOperations elasticsearchTemplate() {
        return new ElasticsearchTemplate(client());
    }
}

但显然没有解决我的多环境问题。

我也尝试过对主机和端口变量使用@Value 注解,但没有成功。

我如何转换以上内容以从应用程序属性文件中读取其值或根据我要运行的配置文件选择不同的@PropertySource 文件?

spring.data.elasticsearch.properties.host = 10.10.1.10
spring.data.elasticsearch.properties.port = 9300

谢谢

最佳答案

删除您的配置类和属性。

添加如下依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

只需将 spring.data.elasticsearch 属性添加到 application-prod.propertiesapplication-dev.properties 并更改所需的环境。这在 ElasticSearch section 中有描述。 Spring Boot 指南。

spring.data.elasticsearch.cluster-nodes=10.10.1.10:9300

这两个文件中的值当然会有所不同(或者将默认值放在 application.properties 中并简单地用 application-dev.properties 覆盖。

Spring Boot 将基于spring.profiles.active load the desired properties文件。

没有必要绕过自己。

关于java - Spring Boot Elasticsearch 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32837507/

相关文章:

java - 线程中的异常 "main"java.lang.NumberFormatException : For input string: "1"

elasticsearch - Kibana:如何仅显示搜索词周围的有限行/单词,而不显示完整文档?

elasticsearch - 如何使用 elasticsearch-py 附加到 Elasticsearch 中的数组

firebase - ElasticSearch 排序给出 fielddata 错误

Java API实现Elasticsearch中script_fields的查询

java - 诺曼底登陆计数器 Java

java - java中的静态方法继承

spring-boot - JHipster 微服务 CORS

java - Spring 启动 : Unable to start embedded Tomcat servlet container

spring-boot - 如果在同一个 Jar 中,为什么 Jars in Jars 不能看到 Jars 中其他 Jars 的内容?