4

我想知道如何使用 Spring Boot 在 HashiCorp Consul 中共享一些属性,我读到了依赖项“spring-cloud-consul-config”,但我找不到如何从那里加载包含所有属性文件的文件夹。

使用 Spring Cloud Config Server 这是可能的,例如:

spring:  
  profiles:
    active: native
  cloud:
    config:
      server:
        native: 
          searchLocations: file:C:/springbootapp/properties/

但是,如何在 Spring Cloud Config Consul 中做到这一点?

4

1 回答 1

2

假设您在标准端口上运行 consul,则使用 spring boot 不需要太多配置。整个代码粘贴在下面(没有其他配置文件)。

对我来说,棘手的部分是弄清楚键/值应该如何存储在 consul 中,以便 Spring Boot 应用程序可以看到。文档中有一些信息,但我认为这有点误导。

为了回答您的问题,我将值放在 consul 内的键“config/bootstrap/key1”下,以使以下示例正常工作。

这是一个对我有用的示例代码:

pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>1.3.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-all</artifactId>
    <version>1.0.0.M5</version>
</dependency>

应用程序.java

@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class Application {

    @Autowired
    private Environment env;

    @RequestMapping("/")
    public String home() {
        return env.getProperty("key1");
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}
于 2016-01-18T04:51:40.863 回答