SpringCloud之配置中心-Config

素颜马尾好姑娘i 2023-07-17 15:58 198阅读 0赞

Config-Server

Spring Cloud Config 是 Spring Cloud 团队创建的一个全新项目,用来为分布式系统中的基础设施和微服务应用提供集中化的外部配置支持, 它分为服务端与客户端两个部分。服务端称为分布式配置中心, 它是一个独立的微服务应用, 用来连接配置仓库并为客户端提供获取配置信息、 加密/解密信息等访问接口;客户端微服务架构中的各个微服务应用或基础设施, 它们通过指定的配置中心来管理应用资源与业务相关的配置内容,并在启动的时候从配置中心获取和加载配置信息。
在这里插入图片描述

Spring Cloud Config 实现了对服务端和客户端中环境变量和属性配置的抽象映射, 所以它除了适用于 Spring 构建的应用程序之外,也可以在任何其他语言运行的应用程序中使用。 由于 Spring Cloud Config 实现的配置中心默认采用 Git 来存储配置信息, 所以使用 Spring Cloud Config 构建的配置服务器,天然就支持对微服务应用配置信息的版本管理, 并且可以通过 Git 客户端工具来方便地管理和访问配置内容。 当然它也提供了对其他存储方式的支持, 比如 SVN 仓库、 本地化文件系统。

快速入门

配置中心服务

  • 在码云(GITEE)新建配置文件(可选GitHub、GitLab)

在码云新建项目config-server,在新项目下新建配置文件夹config,在config下创建application-test.properties,配置文件命名规则应尽可能使用:{application}-{profile}.{properties|yml}

在这里插入图片描述

  • config-server/config/application-test.properties

    name=mask
    age=18

  • pom.xml


    org.springframework.cloud
    spring-cloud-config-server
  • 项目中application.properties

    server.port=8081
    spring.cloud.config.server.git.uri=https://gitee.com/mask_0407/config-server.git
    spring.cloud.config.server.git.username=** #码云账号
    spring.cloud.config.server.git.password=** #码云密码
    spring.cloud.config.server.git.search-paths=/config

  • App.java

    @SpringBootApplication
    @EnableConfigServer
    public class App {

    1. public static void main(String[] args) {
    2. SpringApplication.run(App.class, args);
    3. }

    }

启动项目后访问:http://localhost:8081/application-test.properties
在这里插入图片描述

Config-Client

  • pom.xml

    1. <dependency>
    2. <groupId>org.springframework.cloud</groupId>
    3. <artifactId>spring-cloud-starter-config</artifactId>
    4. </dependency>
    5. <!--ConfigurationProperties类所需依赖,手动添加的-->
    6. <dependency>
    7. <groupId>org.springframework.boot</groupId>
    8. <artifactId>spring-boot-configuration-processor</artifactId>
    9. <optional>true</optional>
    10. </dependency>
  • 码云中application-test.properties

    server.port = 8082
    name=mask
    age=18

  • bootstrap.properties

    server.port = 8082
    spring.application.name = application #对应application-test.properties 中的application
    spring.cloud.config.profile = test #对应application-test.properties 中的test
    spring.cloud.config.uri=http://localhost:8081 # config-server 地址

    开启所有的健康检查

    management.endpoints.web.exposure.include=*

  • AppClient

    @SpringBootApplication
    @EnableDiscoveryClient
    @RestController
    public class AppClient {

    1. @Value("${server.port}")
    2. private String port;
    3. public static void main(String[] args) {
    4. SpringApplication.run(AppClient.class, args);
    5. }
    6. @RequestMapping("print")
    7. public String print() {
    8. return port;
    9. }

    }

启动项目访问http://localhost:8082/print
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,198人围观)

还没有评论,来说两句吧...

相关阅读