Spring Cloud学习笔记(十)-配置中心Config组件从GitHub读取配置文件 - Go语言中文社区

Spring Cloud学习笔记(十)-配置中心Config组件从GitHub读取配置文件


说明:本文仅作为本人学习<<深入理解Spring Cloud与微服务构建>>一书的学习笔记,所有代码案例及文字描述均参考该书,不足之处,请留言指正,不胜感激.
一.为什么要使用Config组件?
  我觉得主要有两点,方便配置统一管理以及在更改配置时不用重启服务.
二.搭建Config Server服务
  首先,我们需要了解的是,Config Server既可以通过本地读取配置文件,也可以通过远程仓库读取配置文件,配置稍有不同,这里只演示从GitHub读取配置文件.
  我们先创建一个Module工程,取名config-server,然后在pom文件中引入Config Server的起步依赖spring-cloud-config-server,以及Eureka Client的起步依赖spring-cloud-starter-eureka,如下:

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

  接着,在启动类上加上@EnableConfigServer,开启Config Server的功能,如下:

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

  最后,在application.yml中做相关的配置,定义服务名,端口,将服务注册到Eureka Server,以及Config的配置,如下:

spring:
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          uri: https://github.com/fly-zhyu/spring-cloud.git
          search-paths: project-config
          username: my username
          password: my password
server:
  port: 8787 
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
  instance:
    prefer-ip-address: true
    instance-id: ${spring.cloud.client.ipAddress}:${server.port}

  综上,一个Config Server就搭建好了.
三.新建一个目录来存放配置文件
  首先看下我们的项目结构:
这里写图片描述
我们新建了一个project-config的目录来存放我们的配置文件.
四.修改消费者服务
  首先,我们引入Config Client的起步依赖,如下:

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

  其次,我们将消费者服务的配置文件移动到project-config中,并调整配置如下:
这里写图片描述
  然后,我们修改消费者服务配置文件,首先介绍下bootstrap.yml文件,bootstrap相对于application具有优先执行的顺序,Config组件最终是通过config.name-config.profile来匹配对应配置文件的,如下:
这里写图片描述
  最后我们依次启动eureka-server,config-server,customer-server,会发现启动成功,访问http://localhost:8764/customer/value, 如下:
这里写图片描述
这里写图片描述
说明我们成功的从GitHub上获取到了配置,这里我们来梳理一下,我们先创建了一个Config Server,并将它注册到Eureka Server,并在其中配置好配置文件在GitHub上的存放路径,接着我们将配置文件上传到GitHub的对应目录下.当我们启动customer-server时,服务器先加载bootstrap文件,将服务注册到Eureka,并获取其他服务的注册列表,所以我们可以通过service-id: config-server找到配置服务,再通过配置服务连接到GitHub,然后匹配到对应的配置文件(config.name-config.profile),从而完成整个流程.

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/fly_zhaohy/article/details/81044425
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-07 22:33:02
  • 阅读 ( 1299 )
  • 分类:Go开源项目

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢