十次方之springcould学习记录(config,bus入门)

集中配置组件SpringCloudConfig

在分布式系统中,由于服务数量巨多,为了方便服务配置文件统一管理,实时更新,所 以需要分布式配置中心组件。在Spring Cloud中,有分布式配置中心组件spring cloud config ,它支持将配置文件放在远程Git仓库 中。在spring cloud config 组件中,分两个角色,一是config server,二是config client。

Config Server是一个可横向扩展、集中式的配置服务器,它用于集中管理应用程序各个 环境下的配置,默认使用Git存储配置文件内容,也可以使用SVN存储,或者是本地文件 存储。

Config Client是Config Server的客户端,用于操作存储在Config Server中的配置内容。 微服务在启动时会请求Config Server获取配置文件的内容,请求到后再启动容器。
详细内容看在线文档: https://springcloud.cc/spring-cloud-config.html

第一步
先在gitee 或者github上创建仓库tensquare-config 将之前我们写的配置文件改成模块名-dev.yml(这里名称可以设置 后面再说) 然后全部放入仓库

第二步配置config server微服务 我们所有的微服务都作为config client从这个模块中取配置信息
(1).创建工程模块 配置中心微服务 tensquare_config加入maven依赖

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

十次方之springcould学习记录(config,bus入门)

这时我们启动这个服务 访问:http://localhost:12000/base-dev.yml 可以看到配置内容

第三步配置config client 以base工程举例

在tensquare_base工程添加依赖

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

因为我们需要从config server中读取配置文件信息 (config server从gitee获取)所以 需要配置server地址

添加bootstrap.yml ,删除application.yml (前提是已经将配置文件放入gitee)

spring:
  cloud:
    config:
      name: base
      profile: dev
      label: master
      uri: http://127.0.0.1:12000

启动工程tensquare_eureka tensquare_config tensquare_base,
访问
发现可以正常运行http://localhost:9001/label

消息总线组件SpringCloudBus

如果我们更新码云中的配置文件,那客户端工程是否可以及时接受新的配置信息 呢?我们现在来做有一个测试,修改一下码云中的配置文件中mysql的端口 ,然后测试 http://localhost:9001/label 数据依然可以查询出来,证明修改服务器中的配置并没有更 新立刻到工程,只有重新启动程序才会读取配置。 那我们如果想在不重启微服务的情况 下更新配置如何来实现呢? 我们使用SpringCloudBus来实现配置的自动更新。
十次方之springcould学习记录(config,bus入门)

首先配置服务端
1.修改tensquare_config工程的pom.xml,引用依赖

 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-bus</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream-binder-rabbit</artifactId>
        </dependency>

2.修改application.yml ,添加配置

  rabbitmq:
    host: 192.168.37.133
management: #暴露触发消息总线的地址
  endpoints:
    web:
      exposure:
        include: bus-refresh

配置客户端我们还是以基础模块为例,加入消息总线
1.导入依赖

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

2.在码云的配置文件中配置rabbitMQ的地址:

   rabbitmq:
        host: 192.168.37.133

注意事项 这里的刷新配置 只会对框架定义的配置信息修改会自动刷新 如果时自定义的配置信息 需要在启动类中加入注解@RefreshScope
当我们改动配置文件时 需要通过post请求 Url: http://127.0.0.1:12000/actuator/bus-refresh
这时客户端就会自动读取改动后的配置文件