Spring Cloud Config 入门学习

前言

Spring Cloud Config 为分布式系统中的外部配置提供服务器和客户端支持。方便部署与运维。

Config 分为 客户端、服务端。

服务端也称分布式配置中心,是一个独立的微服务应用,用来连接配置服务器并为客户端提供获取配置信息,加密/解密信息等访问接口。

客户端则是通过指定配置中心来管理应用资源,以及与业务相关的配置内容,并在启动的时候从配置中心获取和加载配置信息。默认采用 git,并且可以通过 git 客户端工具来方便管理和访问配置内容。

优点:

  1. 集中管理配置文件;
  2. 不同环境不同配置,动态化的配置更新;
  3. 运行期间,不需要去服务器修改配置文件,服务会想配置中心拉取自己的信息;
  4. 配置信息改变时,不需要重启即可更新配置信息到服务;
  5. 配置信息以 rest 接口暴露。

代码

https://gitee.com/xxxxxx/SpringCloudDemo.git 下创建 microservicecloud-config 目录,

创建 application.yml ,内容:

spring:
  profiles:
    active:
    - dev
---
spring:
  profiles: dev     #开发环境
  application: 
    name: microservicecloud-config-demo-dev


hello:
   world: developer
---
spring:
  profiles: test   #测试环境
  application: 
    name: microservicecloud-config-demo-test
#  请保存为UTF-8格式
 
info: study.....

pom.xml

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

application.yml

server: 
  port: 3000
  
spring:
  application:
    name:  microservicecloud-config
  cloud:
    config:
      server:
        git:
          uri: https://gitee.com/xxxxxx/SpringCloudDemo.git  #GitHub上面的git仓库名字
          search-paths:
            - microservicecloud-config  # 指定去具体的目录中找到配置文件。 
                                        # SpringCloudDemo.git 管理许多的微服务的配置,每个微服务去指定的目录查找属于自己的配置文件
      label: master   # 如果默认值是 master,可以省略

在这里插入图片描述

如上图所示, 在https://gitee.com/xxxxxx/SpringCloudDemo.git 下有多个目录,对应的是多个微服务的配置文件, 通过 参数 search-paths 指定一个或多个配置文件。

ConfigServerApplication.java

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

测试

访问: 127.0.0.1.3000/application-dev.yml
在这里插入图片描述

访问: 127.0.0.1.3000/application-test.yml
在这里插入图片描述

Config Client

在 git 上创建 microservicecloud-provider-dept 目录,并添加 application.yml 文件

在这里插入图片描述

pom.xml :

<!-- SpringCloudConfig配置 -->
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-config</artifactId>
</dependency> 

bootstrap.yml :

spring: 
  cloud: 
    config: 
      name: microservicecloud-provider-dept      # 需要从 github 上读取的资源名称,注意没有 yml 后缀名
      profile: dev 
      label: master 
      uri: http://127.0.0.1.com:3000      # SpringCloudConfig 获取的服务地址

主启动类 : DeptProvider

@SpringBootApplication
@EnableEurekaClient 		// 本服务启动后会自动注册进eureka服务中
@EnableDiscoveryClient 		// 服务发现
public class DeptProvider {
	public static void main(String[] args) {
		SpringApplication.run(DeptProvider.class, args);
	}
}

猜你喜欢

转载自blog.csdn.net/xiaojin21cen/article/details/107381384