使用springcloud-config统一管理配置文件

新建config工程,导入依赖,config工程需要作为一个服务注册到eureka上,这里我使用了父工程统一管理依赖,就不用声名版本了

<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>
    </dependencies>

启动类添加注解

@SpringBootApplication
@EnableDiscoveryClient
@EnableConfigServer

config工程的配置文件

spring:
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          uri: https://gitee.com/liuyifengmvc/cloud-config
          username: 用户名
          password: 密码
          basedir: 这里可以不用填写(有默认值),填写了的话码云的的配置文件会被拉取到你指定的目录下
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

新建一个工程,导入依赖

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency> 

其他工程直接通过config这个服务拉取配置文件,这个配置文件的spring.application.name+profile拼接起来的名字就是你要拉取的具体的配置文件名,这里拉取的就是order-dev.yml

spring:
  application:
    name: order
  cloud:
    config:
      discovery:
        service-id: CONFIG-SERVER
        enabled: true
      enabled: true  //这里默认为true可以不用配置
      profile: dev

还有就是客户端的配置文件名尽量使用bootstrap.yml命名,这个是最先加载的配置文件,避免遇到一些启动时的错误

比如当该客户端涉及到对数据访问层的操作,

应用启动时会自动加载数据库的一些配置,

这时你的配置文件需要从码云拉取,

这时就会出现错误,所以需要使用bootstrap.yml来管理配置文件拉取

另外我自己也采坑了就是

我是用application.yml配置去eureka拉取config-server获取配置文件出现的问题

 

c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8888
Connect Timeout Exception on Url - http://localhost:8888. Will be trying the next url if available
Could not locate PropertySource: I/O error on GET request for "http://localhost:8888/product/dev":
      Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect

 

我的config-server地址是在8080端口他却去8888端口找,8888端口时是当客户端连接不上eureka时默认找的端口

 

于是我把application.yml改名为bootstrap.yml,结果就成功了,这应该就是配置文件加载的顺序的原因吧

posted @ 2019-05-12 17:37  不爱笑青年  阅读(1446)  评论(0编辑  收藏  举报