Spring Cloud Config使用详解

LD is tigger forever,CG are not brothers forever, throw the pot and shine.
Modesty is not false, solid is not naive, treacherous but not deceitful, stay with good people, and stay away from poor people.
talk is cheap, show others the code,Keep progress,make a better result.

目录

概述

但往往在微服务架构中,需要维护大量的配置文件,在开发、测试、生产环境,这些配置文件又有所不同,同时还希望能做到修改配置文件时,微服务能够不停止服务。

也就是说在微服务架构中,对于配置文件,通常有如下的需求

配置文件集中管理
不同环境不同配置
运行期间可动态调整配置

架构特性

设计思路

实现思路分析

创建config client
下面以hello项目改造为例,说下client端如何从config server中获取配置。

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

在配置文件bootstrap.yml中添加如下配置

spring:
  application:
    name: hello
  cloud:
    config:
      uri: http://user:123456@localhost:8090/
      profile: dev
      label: master

    @Value("${profile}")
    private String profile;

    @GetMapping("/profile")
    public String  profile(){
        return this.profile;
    }

启动hello项目,输入http://localhost:8000/profile即可在界面上看到dev-1.0的输出。说明客户端正常读取了指定的配置文件内容。

配置刷新
要在微服务运行期间动态刷新配置,可以通过调用/refresh实现,但这样只能针对单个服务,而且要手动操作;如果通过消息中间件,可以将刷新事件广播到所有相关的微服务,从而做到自动刷新。

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <version>1.5.6.RELEASE</version>
        </dependency>`
endpoints:
  refresh:
    enabled: true
    sensitive: false

修改配置文件hello-dev.yml内容,改为dev-1.0-refresh,提交到gitlab中
执行curl -X POST http://localhost:8000/refresh 或者用webhook提交该请求
浏览器输入http://localhost:8000/profile查看输出,发现内容已经更改为dev-1.0-refresh

Spring Cloud Bus 使用 详解

借助Spring Cloud Bus,可以将配置变更事件广播到相关微服务,从而使得相关微服务能够自动刷新配置。

那么刷新的事件可以从单个的服务发起,这样可以将配置更新事件广播到同类服务集群,如果N个微服务集群要更新服务,那么也要操作N次。而从config server发起刷新,则所有相关集群自动刷新配置,后一种明显更好。

config-server 配置spring-cloud-bus

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

启动项目configserver
修改配置文件hello-dev.yml内容为dev-1.0-bus并提交到gitlab
执行curl -X POST http://user:123456@localhost:8090/bus/refresh刷新配置
浏览器输入http://localhost:8000/profile
发现内容变为dev-1.0-bus,说明自动化刷新已生效。

相关工具如下:

实验效果:(解决思路)

分析:

小结:

主要讲述了一些Spring Cloud Config使用详解,里面有许多不足,请大家指正~

参考资料和推荐阅读

1.链接: 参考资料.
2.链接: 参考资料.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

执于代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值