springcloud-服务读取Config配置中心

  1.新建一个模块,用于读取配置中心的配置

  2.添加依赖

<dependencies>
        <!-- 若要读取configServer的配置信息,需要添加configCilent的依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>cn.aib.springcloud</groupId>
            <artifactId>springclud-api-common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

  3.添加配置;这次新建不是application.yml,而是bootstrap.yml,两者的区别:

    1. bootstrap.yml优先applicaiton.yml先被加载执行;

    2. bootstrap.yml配置一些系统级别的配置。而applicaiton.yml配置一些用户级别的配置。

  目前我们这种情况,在bootstrap.yml配置一些信息用于读取配置中心的配置内容。在applicaiton.yml配置自己私有的配置。这样的好处能 配置分明,不用全部挤在一个配置文件里

server:
  port: 3355

spring:
  application:
    name: config-client
  cloud:
    config:
      label: main #表示分支名;这里不再是master,是main
      name: config  #配置文件的名称;比如github上面的config-dev.yml,那配置文件名称为config
      profile: dev  #文件的开发环境
      uri: http://localhost:3344 #配置中心的URL
eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka

  4.主启动

@SpringBootApplication
@EnableEurekaClient
public class ConfigClient3355Application {
    public static void main(String[] args) {
        SpringApplication.run(ConfigClient3355Application.class, args);
    }
}

  5.业务

@RestController
public class ConfigClientController {

    @Value("${config.info}")
    private String configInfo;

    @GetMapping("/configInfo")
    public String getConfigInfo(){
        return configInfo;
    }

}

  6.测试;访问http://localhost/configinfo

原文地址:https://www.cnblogs.com/ibcdwx/p/14449007.html